You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
81 lines
2.1 KiB
81 lines
2.1 KiB
12 years ago
|
<?php
|
||
|
|
||
|
namespace yiiunit\framework\helpers;
|
||
|
|
||
10 years ago
|
use yii\base\Model;
|
||
12 years ago
|
use yii\helpers\Json;
|
||
11 years ago
|
use yiiunit\TestCase;
|
||
12 years ago
|
use yii\web\JsExpression;
|
||
12 years ago
|
|
||
11 years ago
|
/**
|
||
|
* @group helpers
|
||
|
*/
|
||
12 years ago
|
class JsonTest extends TestCase
|
||
12 years ago
|
{
|
||
11 years ago
|
public function testEncode()
|
||
|
{
|
||
|
// basic data encoding
|
||
|
$data = '1';
|
||
|
$this->assertSame('"1"', Json::encode($data));
|
||
12 years ago
|
|
||
11 years ago
|
// simple array encoding
|
||
|
$data = [1, 2];
|
||
|
$this->assertSame('[1,2]', Json::encode($data));
|
||
|
$data = ['a' => 1, 'b' => 2];
|
||
|
$this->assertSame('{"a":1,"b":2}', Json::encode($data));
|
||
12 years ago
|
|
||
11 years ago
|
// simple object encoding
|
||
|
$data = new \stdClass();
|
||
|
$data->a = 1;
|
||
|
$data->b = 2;
|
||
|
$this->assertSame('{"a":1,"b":2}', Json::encode($data));
|
||
12 years ago
|
|
||
11 years ago
|
// expression encoding
|
||
|
$expression = 'function () {}';
|
||
|
$data = new JsExpression($expression);
|
||
|
$this->assertSame($expression, Json::encode($data));
|
||
12 years ago
|
|
||
11 years ago
|
// complex data
|
||
|
$expression1 = 'function (a) {}';
|
||
|
$expression2 = 'function (b) {}';
|
||
|
$data = [
|
||
|
'a' => [
|
||
|
1, new JsExpression($expression1)
|
||
|
],
|
||
|
'b' => new JsExpression($expression2),
|
||
|
];
|
||
|
$this->assertSame("{\"a\":[1,$expression1],\"b\":$expression2}", Json::encode($data));
|
||
11 years ago
|
|
||
11 years ago
|
// https://github.com/yiisoft/yii2/issues/957
|
||
|
$data = (object) null;
|
||
|
$this->assertSame('{}', Json::encode($data));
|
||
10 years ago
|
|
||
|
// JsonSerializable
|
||
|
$data = new JsonModel();
|
||
|
$this->assertSame('{"json":"serializable"}', Json::encode($data));
|
||
11 years ago
|
}
|
||
12 years ago
|
|
||
11 years ago
|
public function testDecode()
|
||
|
{
|
||
|
// basic data decoding
|
||
|
$json = '"1"';
|
||
|
$this->assertSame('1', Json::decode($json));
|
||
12 years ago
|
|
||
11 years ago
|
// array decoding
|
||
|
$json = '{"a":1,"b":2}';
|
||
|
$this->assertSame(['a' => 1, 'b' => 2], Json::decode($json));
|
||
12 years ago
|
|
||
11 years ago
|
// exception
|
||
|
$json = '{"a":1,"b":2';
|
||
|
$this->setExpectedException('yii\base\InvalidParamException');
|
||
|
Json::decode($json);
|
||
|
}
|
||
12 years ago
|
}
|
||
10 years ago
|
|
||
|
class JsonModel extends Model implements \JsonSerializable
|
||
|
{
|
||
|
function jsonSerialize()
|
||
|
{
|
||
|
return ['json' => 'serializable'];
|
||
|
}
|
||
|
}
|