public function testWithStdLibFunction() { $function = function ($lib, $parameter1, $parameter2) { return [$lib('+', $parameter1, $parameter2), $lib('-', $parameter1, $parameter2), $lib('*', $parameter1, $parameter2), $lib('/', $parameter1, $parameter2), $lib('sqrt', $parameter1)]; }; $resultFunction = LJSON::withStdLib($function); $this->assertEquals([3, -1, 2, 0.5, 1], $resultFunction(1, 2)); $this->assertEquals([13, -3, 40, 5 / 8, sqrt(5)], $resultFunction(5, 8)); $this->assertEquals([-12, 12, 0, 0, sqrt(0)], $resultFunction(0, -12)); }
$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;