Skip to content

Commit

Permalink
Merge pull request #37 from WebFiori/dev
Browse files Browse the repository at this point in the history
Added Support for Storing Json Output
  • Loading branch information
usernane authored Feb 11, 2023
2 parents b53e318 + c08ed0f commit ced4660
Show file tree
Hide file tree
Showing 5 changed files with 95 additions and 12 deletions.
1 change: 1 addition & 0 deletions tests/loader.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
}
define('ROOT', $rootDir);
echo 'Root Directory: \''.$rootDir.'\'.'."\n";
require_once $rootDir.'webfiori'.$DS.'json'.$DS.'JsonException.php';
require_once $rootDir.'webfiori'.$DS.'json'.$DS.'JsonConverter.php';
require_once $rootDir.'webfiori'.$DS.'json'.$DS.'CaseConverter.php';
require_once $rootDir.'webfiori'.$DS.'json'.$DS.'Property.php';
Expand Down
28 changes: 23 additions & 5 deletions tests/webfiori/tests/json/JsonTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,26 @@
use PHPUnit\Framework\TestCase;

class JsonTest extends TestCase {
/**
* @test
*/
public function testToJsonFile00() {
$json = new Json();
$json->toJsonFile('json-file', ROOT.DIRECTORY_SEPARATOR.'json-output');
$outputPath = ROOT.DIRECTORY_SEPARATOR.'json-output'.DIRECTORY_SEPARATOR.'json-file.json';
$this->assertTrue(file_exists($outputPath));
}
/**
* @test
* @depends testToJsonFile00
*/
public function testToJsonFile01() {
$outputPath = ROOT.DIRECTORY_SEPARATOR.'json-output'.DIRECTORY_SEPARATOR.'json-file.json';
$this->expectException(\Exception::class);
$this->expectExceptionMessage("File already exist: '$outputPath'");
$json = new Json();
$json->toJsonFile('json-file', ROOT.DIRECTORY_SEPARATOR.'json-output');
}
/**
* @test
*/
Expand Down Expand Up @@ -610,11 +630,11 @@ public function testDecode06() {
* @test
*/
public function testDecode07() {
$this->expectException(\webfiori\json\JsonException::class);
$this->expectExceptionMessage('Syntax error');
$this->expectExceptionCode(4);
$jsonStr = '{prop-1:1}';
$decoded = Json::decode($jsonStr);
$this->assertTrue(gettype($decoded) == 'array');
$this->assertEquals(4,$decoded['error-code']);
$this->assertEquals('Syntax error',$decoded['error-message']);
}
/**
* @test
Expand Down Expand Up @@ -679,8 +699,6 @@ public function testDecode08() {
*/
public function testFromFile00() {
$this->assertNull(Json::fromJsonFile(ROOT.DIRECTORY_SEPARATOR.'not-exist.json'));
$arr = Json::fromJsonFile(ROOT.DIRECTORY_SEPARATOR.'tests'.DIRECTORY_SEPARATOR.'Obj0.php');
$this->assertTrue(gettype($arr) == 'array');
$jsonx = Json::fromJsonFile(ROOT.DIRECTORY_SEPARATOR.'tests'.DIRECTORY_SEPARATOR.'composer.json');
$this->assertTrue($jsonx instanceof Json);
$packagesArr = $jsonx->get('packages');
Expand Down
9 changes: 6 additions & 3 deletions webfiori/json/CaseConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,10 +124,10 @@ private static function _toSnakeOrKebab($value, $from, $to) {
$retVal = '';
$isNumFound = false;
$snakeOrKebabFound = false;

for ($x = 0 ; $x < strlen($attr1) ; $x++) {
$char = $attr1[$x];

if ($char == $to) {
$snakeOrKebabFound = true;
$retVal .= $char;
Expand All @@ -143,7 +143,7 @@ private static function _toSnakeOrKebab($value, $from, $to) {
private static function addChar($x, &$isNumFound, $to, $char, &$snakeOrKebabFound) {
$isUpper = self::_isUpper($char);
$retVal = '';

if (($isUpper || $isNumFound) && $x != 0 && !$snakeOrKebabFound) {
$retVal .= $to.strtolower($char);
} else if ($isUpper && $x == 0) {
Expand All @@ -156,11 +156,13 @@ private static function addChar($x, &$isNumFound, $to, $char, &$snakeOrKebabFoun
}
$snakeOrKebabFound = false;
$isNumFound = false;

return $retVal;
}

private static function addNumber($x, &$isNumFound, $to, $char, &$snakeOrKebabFound) {
$retVal = '';

if ($x == 0) {
$isNumFound = true;
$retVal .= $char;
Expand All @@ -171,6 +173,7 @@ private static function addNumber($x, &$isNumFound, $to, $char, &$snakeOrKebabFo
$retVal .= $to.$char;
}
$isNumFound = true;

return $retVal;
}
}
58 changes: 54 additions & 4 deletions webfiori/json/Json.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
*/
namespace webfiori\json;

use Exception;
use InvalidArgumentException;
/**
* A class that can be used to create well formatted JSON strings.
Expand Down Expand Up @@ -202,6 +203,7 @@ public function add(string $key, $value, $arrayAsObj = false) {
$this->addObject($key, $value) ||
$this->addNull($key);
}

return true;
}
/**
Expand Down Expand Up @@ -448,10 +450,7 @@ public static function decode($jsonStr) {
return $jsonXObj;
}

return [
'error-code' => json_last_error(),
'error-message' => json_last_error_msg()
];
throw new JsonException(json_last_error_msg(), json_last_error());
}
/**
* Escape JSON special characters from string.
Expand Down Expand Up @@ -665,6 +664,57 @@ public function setPropsStyle($style) {
}
}
}
/**
* Attempt to write the generated JSON to a .json file.
*
* @param string $fileName The name of the file at which JSON output will be
* sent to. If the file does not exist, the method will attempt to create it.
*
* @param string $path The folder in file system that the file will be created
* at. If does not exist, the method will attempt to create it.
*
* @param bool $override If a file exist in the specified location with same
* name and this parameter is set to true, the method will override existing
* file by deleting it and creating new one.
*
* @throws Exception
*/
public function toJsonFile(string $fileName, string $path, bool $override = false) {
$nameTrim = trim($fileName);

if (strlen($nameTrim) == 0) {
throw new JsonException('Invalid file name: '.$fileName, -1);
}
$pathTrimmed = trim(str_replace('\\', DIRECTORY_SEPARATOR, str_replace('/', DIRECTORY_SEPARATOR, $path)));

if (strlen($pathTrimmed) == 0) {
throw new JsonException('Invalid file path: '.$path, -1);
}

if (!is_dir($pathTrimmed) && !mkdir($pathTrimmed, 0777 , true)) {
throw new JsonException("Unable to create directory '$pathTrimmed'", -1);
}

$fixedName = explode('.', $fileName)[0];
$fullPath = $path.DIRECTORY_SEPARATOR.$fixedName.'.json';

$isExist = file_exists($fullPath);

if ($isExist && !$override) {
throw new JsonException("File already exist: '$fullPath'", -1);
} else {
if ($isExist && $override) {
unlink($fullPath);
}
}
$resource = fopen($fullPath, 'wb');

if (!is_resource($resource)) {
throw new JsonException("Unable to open file for writing: '$fullPath'", -1);
}
fwrite($resource, $this->toJSONString());
fclose($resource);
}
/**
* Creates and returns a well formatted JSON string that will be created using
* provided data.
Expand Down
11 changes: 11 additions & 0 deletions webfiori/json/JsonException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php
namespace webfiori\json;

use Exception;
/**
* A class which is thrown to indicate that something is incorrect in JSON.
*
* @author Ibrahim
*/
class JsonException extends Exception {
}

0 comments on commit ced4660

Please sign in to comment.