$ljsonString = \LJSON\LJSON::stringify($func); echo PHP_EOL . $ljsonString . PHP_EOL . PHP_EOL; //(v0,v1,v2) => ([v1,v0('*',v2,2)]) $functionFromClient = \LJSON\LJSON::parseWithStdLib($ljsonString); echo json_encode($functionFromClient(2, 3)) . PHP_EOL; /*************** * parseWithStdLib() * complex example **************/ echo 'parseWithStdLib() complex:' . PHP_EOL; $func = function ($lib, $one, $tow) { return function () use($lib, $one, $tow) { return [$one, $lib('*', $tow, 2)]; }; }; $ljsonString = \LJSON\LJSON::stringify($func); echo PHP_EOL . $ljsonString . PHP_EOL . PHP_EOL; //(v0,v1,v2) => ([v1,v0('*',v2,2)]) $functionFromClient = \LJSON\LJSON::parseWithStdLib($ljsonString); $resultFunction1 = $functionFromClient(2, 3); echo json_encode($resultFunction1()) . PHP_EOL; /*************** * withStdLib() * simple example **************/ echo 'withStdLib() simple:' . PHP_EOL; $func = function ($lib, $one, $tow) { return [$one, $lib('*', $tow, 2)]; }; $resultFunction1 = \LJSON\LJSON::withStdLib($func); echo json_encode($resultFunction1(2, 3)) . PHP_EOL;
<?php require_once "../vendor/autoload.php"; // A random object with a pure function inside. $person = ["name" => "John", "mail" => function ($msg) { return ["author" => "John", "message" => $msg]; }]; $personStr = \LJSON\LJSON::stringify($person); $personVal = \LJSON\LJSON::parse($personStr); $mailFunction = $personVal->mail; $mail = $mailFunction("hello"); // would crash with JSON echo $personStr . "\n"; //{"name":"John","mail":(v0) => ({"author":"John","message":v0})} echo \LJSON\LJSON::stringify($mail) . "\n"; //{"author":"John","message":"hello"}
public function testParseLJsonFunctionInFunctionReturnArrayFunction() { $expectedFunction = function ($aaa) { return function () use($aaa) { return [$aaa]; }; }; $actualFunction = LJSON::parse(LJSON::stringify($expectedFunction)); $expectedFunction2 = $expectedFunction(1); $actualFunction2 = $actualFunction(1); $this->assertEquals($expectedFunction2(), $actualFunction2()); }
/** * @expectedException \LJSON\StringifyException */ public function testNoErrorHandlerPreset() { if (PHP_MAJOR_VERSION < 5 || PHP_MAJOR_VERSION == 5 && PHP_MINOR_VERSION < 5) { $this->markTestSkipped('only works for php >=5.5'); return; } set_error_handler(null); LJSON::stringify(function ($aaa) { return (double) $aaa; }); }