diff --git a/src/main/php/text/json/Json.class.php b/src/main/php/text/json/Json.class.php index d82e53f..cfb9064 100755 --- a/src/main/php/text/json/Json.class.php +++ b/src/main/php/text/json/Json.class.php @@ -1,5 +1,9 @@ read(); + // NOOP + } else if ($input instanceof File) { + $input= new FileInput($input); + } else if ($input instanceof InputStream) { + $input= new StreamInput($input); } else { - return (new StringInput($input))->read(); + $input= new StringInput((string)$input); } + + return $input->read(); } /** * Writes to an output and returns the output * * @param var $value - * @param text.json.Output $output + * @param text.json.Output|io.File|io.stream.OutputStream $output * @return text.json.Output The given output + * @throws lang.IllegalArgumentException */ - public static function write($value, Output $output) { + public static function write($value, $output) { + if ($output instanceof Output) { + // NOOP + } else if ($output instanceof File) { + $output= new FileOutput($output); + } else if ($output instanceof OutputStream) { + $output= new StreamOutput($output); + } else { + throw new IllegalArgumentException('Expected an Output, File or OutputStream, have '.typeof($output)); + } + $output->write($value); return $output; } diff --git a/src/test/php/text/json/unittest/JsonTest.class.php b/src/test/php/text/json/unittest/JsonTest.class.php index 36704c6..02f9692 100755 --- a/src/test/php/text/json/unittest/JsonTest.class.php +++ b/src/test/php/text/json/unittest/JsonTest.class.php @@ -1,8 +1,11 @@ containing('"Test"'))); + } finally { + $file->unlink(); + } + } + + #[Test] + public function read_stream() { + Assert::equals('Test', Json::read(new MemoryInputStream('"Test"'))); + } + #[Test, Expect(FormatException::class)] public function read_malformed_string() { Json::read('this.is.not.json'); @@ -31,6 +54,26 @@ public function write_output() { Assert::equals('"Test"', Json::write('Test', new StringOutput())->bytes()); } + #[Test] + public function write_file() { + $file= new TempFile(); + try { + Assert::equals('"Test"', Files::read(Json::write('Test', $file)->file())); + } finally { + $file->unlink(); + } + } + + #[Test] + public function write_stream() { + Assert::equals('"Test"', Json::write('Test', new MemoryOutputStream())->stream()->bytes()); + } + + #[Test, Expect(IllegalArgumentException::class)] + public function write_incorrect_type() { + Json::write('Test', $this); + } + #[Test] public function of_string() { Assert::equals('"Test"', Json::of('Test'));