2017 © Pedro Peláez
 

yii2-extension yii2-json-behavior

Yii2 json attribute behavior

image

paulzi/yii2-json-behavior

Yii2 json attribute behavior

  • Wednesday, March 21, 2018
  • by PaulZi
  • Repository
  • 4 Watchers
  • 54 Stars
  • 21,754 Installations
  • PHP
  • 5 Dependents
  • 0 Suggesters
  • 7 Forks
  • 2 Open issues
  • 9 Versions
  • 29 % Grown

The README.md

Yii2 json attribute behavior

Auto decode/encode attribute value in json, provide array access and json validator., (*1)

WARNING! From version 2.0.14 Yii has built-in DB JSON-type, and this behavior is no longer required., (*2)

Russian readme, (*3)

Packagist Version Code Coverage Scrutinizer Build Status Total Downloads, (*4)

Install

Install via Composer:, (*5)

composer require paulzi/yii2-json-behavior

or add, (*6)

"paulzi/yii2-json-behavior" : "~1.0.0"

to the require section of your composer.json file., (*7)

Usage

JsonBehavior

Configure your model:, (*8)

use paulzi\jsonBehavior\JsonBehavior;

class Item extends \yii\db\ActiveRecord
{
    public function behaviors() {
        return [
            [
                'class' => JsonBehavior::className(),
                'attributes' => ['params'],
            ],
        ];
    }
}

Now you can access to attribute as array:, (*9)

$item = Item::findOne(1);
$item->params['one'] = 'two';
$item->params['two'] = [];
$item->params['two']['key'] = true;
$item->save();

$item = Item::findOne(1);
echo $item['two']['key']; // true

Set attribute via json string:, (*10)

$item = new Item();
$item->params->set('[2, 4, 42]');
echo $item->params[2]; // 42

Set attribute via array:, (*11)

$item = new Item();
$item->params->set(['test' => ['one' => 1]]);
echo $item->params['test']['one']; // 1

Convert to json string:, (*12)

$item = new Item();
$item->params['test'] = ['one' => false, 'two' => [1, 2, 3]];
var_dump((string)$item->params); // {"one":false,"two":[1,2,3]}

Convert to array:, (*13)

$item = new Item();
$item->params->set('{ "one": 1, "two": null, "three": false, "four": "four" }');
var_dump($item->params->toArray());

Check empty:, (*14)

$item = new Item();
$item->params->set('{}');
var_dump($item->params->isEmpty()); // true

emptyValue

You can set emptyValue option to define an empty JSON value (default null). Can be '{}', '[]'' or null., (*15)

JsonValidator

Configure your model (see behavior config upper):, (*16)

use paulzi\jsonBehavior\JsonValidator;

class Item extends \yii\db\ActiveRecord
{
    public function rules() {
        return [
            [['params'], JsonValidator::className()],
        ];
    }
}

Validate:, (*17)

$item = new Item();
$item->attributes = ['params' => '{ test: }'];
var_dump($item->save()); // false
var_dump($item->errors); // ['params' => ['Value is not valid JSON or scalar']]

You can set merge = true, in this case, instead of replacing all field data of the transmitted data, array_merge() will be applied with old data in the field (which are taken from oldAttributes of ActiveRecord). This option can be apply only with ActiveRecord:, (*18)

use paulzi\jsonBehavior\JsonValidator;

class Item extends \yii\db\ActiveRecord
{
    public function rules() {
        return [
            [['params'], JsonValidator::className(), 'merge' => true],
        ];
    }
}

JsonField

You can use JsonField class for other models:, (*19)

class Item
{
    public $params;

    public function __constructor()
    {
        $this->params = new JsonField();
    }
}

// ...

$item = new Item();
$item->params['one'] = 1;
var_dump((string)$item->params); // {"one":1}

How To

Usage isAttributeChanged() and getDirtyAttributes()

Yii2 does not provide the ability to inject code to check attribute dirty., (*20)

If you need to use methods isAttributeChanged() or getDirtyAttributes(), you can override them in model:, (*21)

/**
 * @inheritdoc
 */
public function isAttributeChanged($name, $identical = true)
{
    if ($this->$name instanceof JsonField) {
        return (string)$this->$name !== $this->getOldAttribute($name);
    } else {
        return parent::isAttributeChanged($name, $identical);
    }
}

/**
 * @inheritdoc
 */
public function getDirtyAttributes($names = null)
{
    $result = [];
    $data = parent::getDirtyAttributes($names);
    foreach ($data as $name => $value) {
        if ($value instanceof JsonField) {
            if ((string)$value !== $this->getOldAttribute($name)) {
                $result[$name] = $value;
            }
        } else {
            $result[$name] = $value;
        }
    }
    return $result;
}

The Versions

21/03 2018

dev-master

9999999-dev

Yii2 json attribute behavior

  Sources   Download

MIT

The Requires

 

The Development Requires

by Avatar PaulZi

json yii2 validator behavior

21/03 2018

v1.0.6

1.0.6.0

Yii2 json attribute behavior

  Sources   Download

MIT

The Requires

 

The Development Requires

by Avatar PaulZi

json yii2 validator behavior

07/11 2017

v1.0.5

1.0.5.0

Yii2 json attribute behavior

  Sources   Download

MIT

The Requires

 

The Development Requires

by Avatar PaulZi

json yii2 validator behavior

06/10 2017

v1.0.4

1.0.4.0

Yii2 json attribute behavior

  Sources   Download

MIT

The Requires

 

The Development Requires

by Avatar PaulZi

json yii2 validator behavior

06/10 2017

v1.0.3

1.0.3.0

Yii2 json attribute behavior

  Sources   Download

MIT

The Requires

 

The Development Requires

by Avatar PaulZi

json yii2 validator behavior

13/08 2017

v1.0.2

1.0.2.0

Yii2 json attribute behavior

  Sources   Download

MIT

The Requires

 

The Development Requires

by Avatar PaulZi

json yii2 validator behavior

13/08 2017

dev-issue4

dev-issue4

Yii2 json attribute behavior

  Sources   Download

MIT

The Requires

 

The Development Requires

by Avatar PaulZi

json yii2 validator behavior

12/12 2016

v1.0.1

1.0.1.0

Yii2 json attribute behavior

  Sources   Download

MIT

The Requires

 

The Development Requires

by Avatar PaulZi

json yii2 validator behavior

17/08 2016

v1.0.0

1.0.0.0

Yii2 json attribute behavior

  Sources   Download

MIT

The Requires

 

The Development Requires

by Avatar PaulZi

json yii2 validator behavior