Skip to content

Commit

Permalink
Added ArrayS::setJsonFormat
Browse files Browse the repository at this point in the history
  • Loading branch information
3nr1c committed Sep 9, 2015
1 parent 2e7b381 commit 4ab2338
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/Structure/ArrayS.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,38 @@ public function setFormat($format) {
}
}

/**
* Takes a string argument that can be either a valid JSON string, or
* a path to a file containing a valid JSON string. If the syntax is
* invalid or the file can't be accessed, an \Exception will be thrown
*
* @param string $format
* @return bool
* @throws \Exception
*/
public function setJsonFormat($format) {
if (!is_string($format)) throw new \Exception("JsonFormat must be a valid json string or a path to a file");

if (file_exists($format)) {
$handler = fopen($format, 'r');
$contents = fread($handler, filesize($format));
fclose($handler);

$format = $contents;
}
$format = trim($format);

$arrayFormatCandidate = json_decode($format, true, 1024);

$error = json_last_error();
if ($error === JSON_ERROR_NONE) {
$this->setFormat($arrayFormatCandidate);
return true;
}

throw new \Exception("Invalid Json format or file");
}

/**
* Parses expressions matching /\[(\d+|\d*\+|\*)?\]/
*
Expand Down
26 changes: 26 additions & 0 deletions tests/ArrayJsonTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

/**
* Created by PhpStorm.
* User: enric
* Date: 9/9/15
* Time: 12:47
*/

use \Structure\ArrayS;

class ArrayJsonTest extends PHPUnit_Framework_TestCase {
public function testJsonStructure() {
$array = new ArrayS();
$array->setJsonFormat(__DIR__ . "/resources/testJsonStructure.json");

$res = $array->check(array(
"id" => 34,
"name" => "John",
"age" => 18,
"marks" => array(8, 7.6, 3, 1, 9, 0, 10, 9.8, 0.4, 4.5)
));

$this->assertTrue($res);
}
}
6 changes: 6 additions & 0 deletions tests/resources/testJsonStructure.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"id": "integer[1,inf)",
"name": "string(3..40)",
"age": "integer[0,120]",
"marks": "float[0,10][]"
}

0 comments on commit 4ab2338

Please sign in to comment.