From 720c68da3d17d57993884fe7bf4d1a2998a1fb0b Mon Sep 17 00:00:00 2001 From: Inhere Date: Tue, 9 Nov 2021 00:02:00 +0800 Subject: [PATCH] update: update json generate class logic --- app/Console/Controller/ConvertController.php | 8 +- app/Console/Controller/StringController.php | 65 ++++++------- app/Helper/KiteUtil.php | 11 +-- app/Lib/Generate/AbstractJsonToCode.php | 42 ++------- app/Lib/Generate/Json/JsonField.php | 16 +++- app/Lib/Generate/Json5Data.php | 97 ++++++++++++++++++++ app/Lib/Parser/Text/TextParser.php | 10 ++ app/Lib/Stream/MapStream.php | 14 +++ 8 files changed, 189 insertions(+), 74 deletions(-) create mode 100644 app/Lib/Generate/Json5Data.php diff --git a/app/Console/Controller/ConvertController.php b/app/Console/Controller/ConvertController.php index f731bca..b9ec612 100644 --- a/app/Console/Controller/ConvertController.php +++ b/app/Console/Controller/ConvertController.php @@ -25,6 +25,7 @@ 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; @@ -32,6 +33,7 @@ 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; @@ -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 @@ -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)); @@ -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'); diff --git a/app/Console/Controller/StringController.php b/app/Console/Controller/StringController.php index cd0fb0e..2fd5955 100644 --- a/app/Console/Controller/StringController.php +++ b/app/Console/Controller/StringController.php @@ -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 = ''; @@ -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"); } } @@ -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 @@ -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; @@ -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"; } diff --git a/app/Helper/KiteUtil.php b/app/Helper/KiteUtil.php index 67d30a7..a5cd389 100644 --- a/app/Helper/KiteUtil.php +++ b/app/Helper/KiteUtil.php @@ -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'); + }); } /** diff --git a/app/Lib/Generate/AbstractJsonToCode.php b/app/Lib/Generate/AbstractJsonToCode.php index e4034b6..5902e32 100644 --- a/app/Lib/Generate/AbstractJsonToCode.php +++ b/app/Lib/Generate/AbstractJsonToCode.php @@ -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; @@ -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; } @@ -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, diff --git a/app/Lib/Generate/Json/JsonField.php b/app/Lib/Generate/Json/JsonField.php index 53dda28..28fc885 100644 --- a/app/Lib/Generate/Json/JsonField.php +++ b/app/Lib/Generate/Json/JsonField.php @@ -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; /** @@ -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 */ diff --git a/app/Lib/Generate/Json5Data.php b/app/Lib/Generate/Json5Data.php new file mode 100644 index 0000000..2a5b13c --- /dev/null +++ b/app/Lib/Generate/Json5Data.php @@ -0,0 +1,97 @@ + + */ + 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; + } +} diff --git a/app/Lib/Parser/Text/TextParser.php b/app/Lib/Parser/Text/TextParser.php index 2a7e4c8..7715b54 100644 --- a/app/Lib/Parser/Text/TextParser.php +++ b/app/Lib/Parser/Text/TextParser.php @@ -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 */ diff --git a/app/Lib/Stream/MapStream.php b/app/Lib/Stream/MapStream.php index c1e8e6e..de25a18 100644 --- a/app/Lib/Stream/MapStream.php +++ b/app/Lib/Stream/MapStream.php @@ -19,6 +19,20 @@ public static function new(array $data): self return new self($data); } + /** + * @param array $data + * + * @return $this + */ + public function load(array $data): self + { + foreach ($data as $key => $value) { + $this->offsetSet($key, $value); + } + + return $this; + } + /** * @param callable(array): string $func * @param bool|mixed $apply