Commit 7c69c914 by Paul Klimov

BaseVarDumper::export() added

parent aa34d312
......@@ -6,6 +6,7 @@
*/
namespace yii\helpers;
use yii\base\Arrayable;
/**
* BaseVarDumper provides concrete implementation for [[VarDumper]].
......@@ -123,4 +124,60 @@ class BaseVarDumper
break;
}
}
public static function export($var)
{
echo static::exportAsString($var);
}
public static function exportAsString($var)
{
self::$_output = '';
self::exportInternal($var, 0);
return self::$_output;
}
private static function exportInternal($var, $level)
{
switch (gettype($var)) {
case 'NULL':
self::$_output .= 'null';
break;
case 'array':
if (empty($var)) {
self::$_output .= '[]';
} else {
$keys = array_keys($var);
$outputKeys = ($keys !== range(0, sizeof($var) - 1));
$spaces = str_repeat(' ', $level * 4);
self::$_output .= '[';
foreach ($keys as $key) {
self::$_output .= "\n" . $spaces . ' ';
if ($outputKeys) {
self::exportInternal($key, 0);
self::$_output .= ' => ';
}
self::exportInternal($var[$key], $level + 1);
self::$_output .= ',';
}
self::$_output .= "\n" . $spaces . ']';
}
break;
case 'object':
if ($var instanceof Arrayable) {
self::exportInternal($var->toArray(), $level);
} elseif ($var instanceof \IteratorAggregate) {
$varAsArray = [];
foreach ($var as $key => $value) {
$varAsArray[$key] = $value;
}
self::exportInternal($varAsArray, $level);
} else {
self::$_output .= serialize($var);
}
break;
default:
self::$_output .= var_export($var, true);
}
}
}
<?php
namespace yiiunit\framework\helpers;
use yii\data\ArrayDataProvider;
use yii\helpers\VarDumper;
use yiiunit\TestCase;
......@@ -17,4 +18,90 @@ class VarDumperTest extends TestCase
$this->assertEquals("stdClass#1\n(\n)", ob_get_contents());
ob_end_clean();
}
/**
* Data provider for [[testExport()]]
* @return array test data
*/
public function dataProviderExport()
{
// Regular :
$data = [
[
'test string',
var_export('test string', true)
],
[
75,
var_export(75, true)
],
[
7.5,
var_export(7.5, true)
],
[
null,
'null'
],
[
true,
'true'
],
[
false,
'false'
],
[
[],
'[]'
],
];
// Arrays :
$var = [
'key1' => 'value1',
'key2' => 'value2',
];
$expectedResult = <<<RESULT
[
'key1' => 'value1',
'key2' => 'value2',
]
RESULT;
$data[] = [$var, $expectedResult];
$var = [
'value1',
'value2',
];
$expectedResult = <<<RESULT
[
'value1',
'value2',
]
RESULT;
$data[] = [$var, $expectedResult];
// Objects :
$var = new \StdClass();
$var->testField = 'Test Value';
$expectedResult = serialize($var);
$data[] = [$var, $expectedResult];
return $data;
}
/**
* @dataProvider dataProviderExport
*
* @param mixed $var
* @param string $expectedResult
*/
public function testExport($var, $expectedResult)
{
$this->assertEquals($expectedResult, VarDumper::exportAsString($var));
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment