Skip to content

Commit

Permalink
update: update json generate class logic
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Nov 8, 2021
1 parent 035bc5c commit 720c68d
Show file tree
Hide file tree
Showing 8 changed files with 189 additions and 74 deletions.
8 changes: 7 additions & 1 deletion app/Console/Controller/ConvertController.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,15 @@
use Symfony\Component\Yaml\Yaml;
use Toolkit\FsUtil\File;
use Toolkit\PFlag\FlagsParser;
use Toolkit\Stdlib\Json;
use function array_pad;
use function array_shift;
use function base_convert;
use function date;
use function file_get_contents;
use function implode;
use function is_file;
use function json_encode;
use function strlen;
use function substr;
use function trim;
Expand Down Expand Up @@ -129,6 +131,7 @@ public function sql2mdCommand(FlagsParser $fs, Output $output): void
* -s,--source string;The source code for convert. allow: FILEPATH, @clipboard;true
* -o,--output The output target. default is stdout.
* --item-sep The item sep char. default is NL.
* --value-num int;The item value number. default get from first line.
* --value-sep The item value sep char. default is SPACE
*
* @param FlagsParser $fs
Expand All @@ -141,6 +144,7 @@ public function textCommand(FlagsParser $fs, Output $output): void

$p = TextParser::new($text);
$p->setItemSep($fs->getOpt('item-sep'));
$p->setFieldNum($fs->getOpt('value-num'));

if ($vSep = $fs->getOpt('value-sep')) {
$p->setItemParser(TextParser::charSplitParser($vSep));
Expand All @@ -162,9 +166,11 @@ public function textCommand(FlagsParser $fs, Output $output): void
$result = $head . "\n" . $line . "\n". implode("\n", $rows);
break;
case 'raw':
default:
$result = $text;
break;
default:
$result = Json::pretty($p->getData());
break;
}

$outFile = $fs->getOpt('output');
Expand Down
65 changes: 34 additions & 31 deletions app/Console/Controller/StringController.php
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,10 @@ public function splitCommand(FlagsParser $fs): void
protected function applyFilters(string $str, array $filters): string
{
foreach ($filters as $filter) {
if ('' === $str) {
break;
}

$args = [];
$argStr = '';

Expand All @@ -213,14 +217,21 @@ protected function applyFilters(string $str, array $filters): string
}
}

if ($filter === 'wrap') {
$str = Str::wrap($str, ...$args);
} elseif ($filter === 'append') {
$str .= $argStr;
} elseif ($filter === 'prepend') {
$str = $argStr . $str;
} else {
throw new InvalidArgumentException("unsupported filter: $filter");
switch ($filter) {
case 'wrap':
$str = Str::wrap($str, ...$args);
break;
case 'append':
$str .= $argStr;
break;
case 'prepend':
$str = $argStr . $str;
break;
case 'replace':
$str = str_replace($args[0], $args[1], $str);
break;
default:
throw new InvalidArgumentException("unsupported filter: $filter");
}
}

Expand Down Expand Up @@ -273,20 +284,23 @@ public function replaceCommand(FlagsParser $fs, Output $output): void
* input '@FILEPATH' - will read from the filepath
*
* @options
* -e, --exclude array;exclude line on contains keywords.
* -m, --match array;include line on contains keywords.
* -t, --trim bool;trim the each line text.
* -e, --exclude array;sub text should not contains keywords.
* -i, --include array;sub text should contains keywords.
* -t, --trim bool;trim the each sub text.
* --each bool;Operate on each substr after split.
* --wrap wrap the each line by the separator
* -j, --join join the each line by the separator
* -c, --cut cut each line by the separator. cut position: L R, eg: 'L='
* -r, --replace array;replace chars for each line
* -r, --replace array;replace chars for each sub text
* -s, --sep The separator char for split contents. defaults is newline(\n).
* -f, --filter array;apply more filter for handle text.
* -f, --filter array;apply filter for handle each sub text.
* allow filters:
* - replace replace substr
* - notEmpty filter empty line
* - min limit min length
* - wrap wrap each line. wrap:'
* - wrap wrap each line. `wrap:'`
* - prepend prepend char each line. `prepend:-`
* - append append char to each line. `append:'`
*
* @param FlagsParser $fs
* @param Output $output
Expand All @@ -309,13 +323,13 @@ public function processCommand(FlagsParser $fs, Output $output): void
}

$ex = $fs->getOpt('exclude');
$in = $fs->getOpt('match');
$in = $fs->getOpt('include');

$trim = $fs->getOpt('trim');
$cut = $fs->getOpt('cut');
$sep = $fs->getOpt('sep', "\n");
//
$replaces = $fs->getOpt('replace');
// filters
$filters = $fs->getOpt('filter');

$cutPos = 'L';
$cutChar = $cut;
Expand Down Expand Up @@ -345,20 +359,9 @@ public function processCommand(FlagsParser $fs, Output $output): void
->filterIf(function (string $line) use ($in) { // include
return Str::has($line, $in);
}, count($in) > 0)
->eachIf(function (string $line) use ($replaces) { // replace
// TODO
// $this->applyFilters($line, $filters);

$froms = $tos = [];
foreach ($replaces as $replace) {
[$from, $to] = explode('/', $replace, 2);
$froms[] = $from;
$tos[] = $to;
}

// vdump($line);
return str_replace($froms, $tos, $line);
}, $replaces);
->eachIf(function (string $line) use ($filters) { // filters
return $this->applyFilters($line, $filters);
}, $filters);

echo $s->implode($sep), "\n";
}
Expand Down
11 changes: 5 additions & 6 deletions app/Helper/KiteUtil.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,11 @@ public static function userConfigDir(string $path = ''): string
*/
public static function newTplEngine(): EasyTemplate
{
// $tplEng = new TextTemplate($text);
$tplEng = new EasyTemplate();

$tplEng->tmpDir = Kite::getTmpPath('tplCache');
// some config
return $tplEng;
return EasyTemplate::new()
->setPathResolver([Kite::class, 'resolve'])
->configThis(function (EasyTemplate $tpl) {
$tpl->tmpDir = Kite::getTmpPath('tplCache');
});
}

/**
Expand Down
42 changes: 8 additions & 34 deletions app/Lib/Generate/AbstractJsonToCode.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Toolkit\Stdlib\Str;
use Toolkit\Stdlib\Type;
use function array_merge;
use function date;
use function dirname;
use function gettype;
use function is_file;
Expand Down Expand Up @@ -103,40 +104,11 @@ public function prepare(): self
throw new InvalidArgumentException('empty source json(5) data for generate');
}

// auto add quote char
if ($json[0] !== '{') {
$json = '{' . $json . "\n}";
}
$jd = Json5Data::new()->loadFrom($json);

$comments = [];
$jsonData = Json5Decoder::decode($json, true);

// has comments chars
if (str_contains($json, '//')) {
$p = TextParser::newWithParser($json, new Json5LineParser())
->withConfig(function (TextParser $p) {
$p->headerSep = "\n//###\n";
})
->setBeforeParseHeader(function (string $header) {
if ($pos = strpos($header, "//##\n")) {
$header = substr($header, $pos + 4);
$header = str_replace("\n//", '', $header);
}
return $header;
})
->parse();

$comments = $p->getStringMap('field', 'comment');
$this->setContexts($p->getSettings());
}
$this->fields = $jd->getFields();
$this->setContexts($jd->getSettings());

foreach ($jsonData as $key => $value) {
$this->fields[$key] = JsonField::new([
'name' => $key,
'type' => gettype($value),
'desc' => $comments[$key] ?? $key,
]);
}
return $this;
}

Expand All @@ -149,9 +121,11 @@ protected function renderTplText(): string
$tplEng = KiteUtil::newTplEngine();

$settings = array_merge([
'user' => OS::getUserName(),
'lang' => 'java',
'user' => OS::getUserName(),
'date' => date('Y-m-d'),
], $this->contexts);
vdump($settings);

$tplVars = [
'ctx' => $settings,
'fields' => $this->fields,
Expand Down
16 changes: 14 additions & 2 deletions app/Lib/Generate/Json/JsonField.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
use Toolkit\Stdlib\Obj\AbstractObj;
use Toolkit\Stdlib\Str;
use Toolkit\Stdlib\Type;
use function gettype;
use function json_encode;
use function preg_match;

/**
Expand All @@ -21,6 +19,20 @@ class JsonField extends AbstractObj implements JsonSerializable
public string $type;
public string $desc;

/**
* @param string $lang
*
* @return string
*/
public function getType(string $lang = 'php'): string
{
if ($lang === 'php') {
return $this->type;
}

return $this->toJavaType();
}

/**
* @return string
*/
Expand Down
97 changes: 97 additions & 0 deletions app/Lib/Generate/Json5Data.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
<?php declare(strict_types=1);

namespace Inhere\Kite\Lib\Generate;

use ColinODell\Json5\Json5Decoder;
use Inhere\Kite\Lib\Generate\Json\JsonField;
use Inhere\Kite\Lib\Parser\Text\Json5LineParser;
use Inhere\Kite\Lib\Parser\Text\TextParser;
use Toolkit\Stdlib\Obj\AbstractObj;
use function gettype;
use function str_replace;
use function strpos;
use function substr;

/**
* class Json5Data
*
* @author inhere
*/
class Json5Data extends AbstractObj
{
private array $settings = [];

/**
* @var array<string, JsonField>
*/
private array $fields = [];

/**
* @param string $json
*
* @return $this
*/
public function loadFrom(string $json): self
{
// auto add quote char
if ($json[0] !== '{') {
$json = '{' . $json . "\n}";
}

$comments = [];
$jsonData = Json5Decoder::decode($json, true);

// has comments chars
if (str_contains($json, '//')) {
$p = TextParser::newWithParser($json, new Json5LineParser())
->withConfig(function (TextParser $p) {
$p->headerSep = "\n//###\n";
})
->setBeforeParseHeader(function (string $header) {
if ($pos = strpos($header, "//##\n")) {
$header = substr($header, $pos + 4);
$header = str_replace("\n//", '', $header);
}
return $header;
})
->parse();

$comments = $p->getStringMap('field', 'comment');
$this->setSettings($p->getSettings());
}

foreach ($jsonData as $key => $value) {
$this->fields[$key] = JsonField::new([
'name' => $key,
'type' => gettype($value),
'desc' => $comments[$key] ?? $key,
]);
}

return $this;
}

/**
* @return array
*/
public function getSettings(): array
{
return $this->settings;
}

/**
* @param array $settings
*/
public function setSettings(array $settings): void
{
$this->settings = $settings;
}

/**
* @return JsonField[]
*/
public function getFields(): array
{
return $this->fields;
}
}
10 changes: 10 additions & 0 deletions app/Lib/Parser/Text/TextParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -671,6 +671,16 @@ public function getText(): string
return $this->text;
}

/**
* @param int $fieldNum
*/
public function setFieldNum(int $fieldNum): void
{
if ($fieldNum > 0) {
$this->fieldNum = $fieldNum;
}
}

/**
* @param bool $parseHeader
*/
Expand Down

0 comments on commit 720c68d

Please sign in to comment.