Skip to content

Commit

Permalink
up: update some for json to java class gen
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Nov 7, 2021
1 parent 1f23d92 commit 7ca5491
Show file tree
Hide file tree
Showing 9 changed files with 82 additions and 87 deletions.
2 changes: 1 addition & 1 deletion app/Console/Component/ContentsAutoReader.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public function read(string $source, array $opts = []): string
$print && Cli::info('try read contents from file: ' . $lFile);
$str = File::readAll($lFile);
} else {
$filepath = Kite::alias($source);
$filepath = Kite::resolve($source);
if ($filepath[0] === '@') {
$filepath = substr($filepath, 1);
}
Expand Down
2 changes: 1 addition & 1 deletion app/Console/Component/ContentsAutoWriter.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public function write(string $contents): bool
Kite::cliApp()->getOutput()->info('write results to file: ' . $this->output);
}

$filepath = Kite::alias($this->output);
$filepath = Kite::resolve($this->output);

// write
File::mkdirSave($contents, $filepath);
Expand Down
11 changes: 5 additions & 6 deletions app/Console/Controller/JsonController.php
Original file line number Diff line number Diff line change
Expand Up @@ -311,20 +311,19 @@ public function toClassCommand(FlagsParser $fs, Output $output): void
'tplDir' => $tplDir,
'tplFile' => $tplFile,
]));
vdump($config);
// vdump($config);
// @user-custom/template/java-service-tpl/req-resp-dto.tpl
$gen = JsonToCode::create($type)
->setSource($json)
->configObj($config)
->setPathResolver([Kite::class, 'alias'])
->configThis($config)
->setPathResolver([Kite::class, 'resolve'])
->prepare();

$output->aList($gen->getFields(), 'field list');

$contents = $gen->generate();

$result = $gen->generate();
$output->colored('------------------ Generated Codes -------------------');
$output->writeRaw($contents);
$output->writeRaw($result);
}

/**
Expand Down
44 changes: 8 additions & 36 deletions app/Helper/KiteUtil.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Inhere\Kite\Helper;

use Inhere\Kite\Kite;
use Inhere\Kite\Lib\Template\EasyTemplate;
use Leuffen\TextTemplate\TextTemplate;
use Toolkit\FsUtil\FS;
use Toolkit\Stdlib\OS;
Expand Down Expand Up @@ -91,45 +93,15 @@ public static function userConfigDir(string $path = ''): string
}

/**
* @param string $text
*
* @return TextTemplate
* @return EasyTemplate
*/
public static function newTplEngine(string $text): TextTemplate
public static function newTplEngine(): EasyTemplate
{
$tplEng = new TextTemplate($text);
// default value on empty. usage: {= ctx.user | default:inhere}
$tplEng->addFilter('default', function ($value, $default) {
if ($value === '') {
return $default;
}
return empty($value) ? $default : $value;
});

// upper first char. usage: {= ctx.user | upFirst}
$tplEng->addFilter('upFirst', function ($value) {
if ($value === '') {
return '';
}
return Str::upFirst($value);
});

// snake to camel. usage: {= ctx.user | toCamel}
$tplEng->addFilter('toCamel', function ($value) {
if ($value === '') {
return '';
}
return Str::toCamel($value);
});

// camel to snake. usage: {= ctx.user | toSnake}
$tplEng->addFilter('toSnake', function ($value) {
if ($value === '') {
return '';
}
return Str::toSnake($value);
});
// $tplEng = new TextTemplate($text);
$tplEng = new EasyTemplate();

$tplEng->tmpDir = Kite::getTmpPath('tplCache');
// some config
return $tplEng;
}

Expand Down
43 changes: 5 additions & 38 deletions app/Lib/Generate/AbstractJsonToCode.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
use function strpos;
use function substr;
use function trim;
use function vdump;

/**
* class AbstractJsonToCode
Expand Down Expand Up @@ -78,7 +79,6 @@ abstract class AbstractJsonToCode

/**
* @return string
* @throws Throwable
*/
public function generate(): string
{
Expand Down Expand Up @@ -142,55 +142,22 @@ public function prepare(): self

/**
* @return string
* @throws Throwable
*/
protected function renderTplText(): string
{
$tplText = $this->readSourceFromFile();
$tplEng = KiteUtil::newTplEngine($tplText);

$tplEng->addFunction(
'needToSnake',
function ($paramArr) {
$name = $paramArr['name'];
if (str_contains($name, '_')) {
return true;
}

if (preg_match('/[A-Z]/', $name)) {
return true;
}

return false;
});

// {toJavaType type=field.type name=field.name}
$tplEng->addFunction(
'toJavaType',
function ($paramArr, $command, $context, $cmdParam, $self) {
$type = $paramArr['type'];
$name = $paramArr['name'];
if ($type === Type::ARRAY) {
return JavaType::OBJECT;
}

if (str_ends_with($name, 'id') || str_ends_with($name, 'Id')) {
return JavaType::LONG;
}

return Str::upFirst($type);
});
$tplEng = KiteUtil::newTplEngine();

$settings = array_merge([
'user' => OS::getUserName(),
], $this->contexts);

vdump($settings);
$tplVars = [
'ctx' => $settings,
'fields' => $this->fields,
];

return $tplEng->apply($tplVars, false);
return $tplEng->renderString($tplText, $tplVars);
}

/**
Expand All @@ -212,7 +179,7 @@ public function generateTo(string $outFile): bool
*
* @return self
*/
public function configObj(array $config): self
public function configThis(array $config): self
{
Obj::init($this, $config);

Expand Down
35 changes: 35 additions & 0 deletions app/Lib/Generate/Json/JsonField.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@

namespace Inhere\Kite\Lib\Generate\Json;

use Inhere\Kite\Lib\Generate\Java\JavaType;
use JsonSerializable;
use Toolkit\Stdlib\Json;
use Toolkit\Stdlib\Obj\AbstractObj;
use Toolkit\Stdlib\Str;
use Toolkit\Stdlib\Type;
use function gettype;
use function json_encode;
use function preg_match;

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

/**
* @return string
*/
public function toJavaType(): string
{
if ($this->type === Type::ARRAY) {
return JavaType::OBJECT;
}

if (str_ends_with($this->name, 'id') || str_ends_with($this->name, 'Id')) {
return JavaType::LONG;
}

return Str::upFirst($this->type);
}

/**
* @return bool
*/
public function isMultiWords(): bool
{
if (str_contains($this->name, '_')) {
return true;
}

if (preg_match('/[A-Z]/', $this->name)) {
return true;
}

return false;
}

/**
* @return array
*/
Expand Down
3 changes: 2 additions & 1 deletion app/Lib/Generate/JsonToJavaClass.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ class JsonToJavaClass extends AbstractJsonToCode
public function generate(): string
{
// todo
$this->contexts['pkgName'] = '';
$this->contexts['pkgName'] = 'YOUR.PKG.NAME';
$this->contexts['className'] = 'YourClass';

return parent::generate();
}
Expand Down
13 changes: 13 additions & 0 deletions app/Lib/Template/EasyTemplate.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,19 @@ public function compileCode(string $code): string
return $this->compiler->compile($code);
}

/**
* @param string $name
* @param callable $handler
*
* @return $this
*/
public function addFilter(string $name, callable $handler): self
{
//
// $this->compiler->addFilter();
return $this;
}

/**
* @param string $open
* @param string $close
Expand Down
16 changes: 12 additions & 4 deletions app/Lib/Template/TextTemplate.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use InvalidArgumentException;
use RuntimeException;
use Throwable;
use Toolkit\FsUtil\Dir;
use Toolkit\Stdlib\Obj;
use Toolkit\Sys\Sys;
Expand All @@ -12,7 +13,9 @@
use function extract;
use function file_exists;
use function file_put_contents;
use function hash;
use function md5;
use function ob_clean;
use function ob_get_clean;
use function ob_start;
use function sprintf;
Expand Down Expand Up @@ -98,9 +101,14 @@ protected function doRenderFile(string $tplFile, array $tplVars): string

ob_start();
extract($tplVars, EXTR_OVERWRITE);
// require \BASE_PATH . '/runtime/go-snippets-0709.tpl.php';
require $tplFile;
return ob_get_clean();
try {
// require \BASE_PATH . '/runtime/go-snippets-0709.tpl.php';
require $tplFile;
return ob_get_clean();
} catch (Throwable $e) {
ob_clean();
throw $e;
}
}

/**
Expand All @@ -113,7 +121,7 @@ protected function doRenderFile(string $tplFile, array $tplVars): string
protected function genTempPhpFile(string $tplCode): string
{
$tmpDir = $this->tmpDir ?: Sys::getTempDir() . '/php-tpl-gen';
$tmpFile = sprintf('%s/%s-%s.php', $tmpDir, date('ymd'), md5($tplCode));
$tmpFile = sprintf('%s/%s-%s.php', $tmpDir, date('ymd_his'), md5($tplCode));

if (!file_exists($tmpFile)) {
Dir::create($tmpDir);
Expand Down

0 comments on commit 7ca5491

Please sign in to comment.