Skip to content

Commit

Permalink
[3.0] 重构各个生成器,使用原生注解 (#608)
Browse files Browse the repository at this point in the history
* 重构生成模型,使用原生注解

* 重构生成 PostgreSQL 模型,使用原生注解

* 模型类生成模版中使用原生注解

* 重命名

* 重构生成门面,使用原生注解

* 重构生成请求上下文代理,使用原生注解

* 优化代码

* 重构控制器生成命令,使用原生注解

* 修复测试

* 完善测试
  • Loading branch information
Yurunsoft authored Oct 27, 2023
1 parent 0a55a95 commit e32aeab
Show file tree
Hide file tree
Showing 63 changed files with 1,088 additions and 798 deletions.
17 changes: 8 additions & 9 deletions .php-cs-fixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@
'concat_space' => [
'spacing' => 'one',
],
'fopen_flags' => false,
'protected_to_private' => false,
'native_function_invocation' => true,
'native_constant_invocation' => true,
'combine_nested_dirname' => true,
'single_quote' => true,
'fopen_flags' => false,
'protected_to_private' => false,
'native_function_invocation' => true,
'native_constant_invocation' => true,
'combine_nested_dirname' => true,
'single_quote' => true,
'single_space_around_construct' => [
'constructs_followed_by_a_single_space' => [
'abstract',
Expand Down Expand Up @@ -121,10 +121,9 @@
'control_structures_opening_brace' => 'next_line_unless_newline_at_signature_end',
],
'nullable_type_declaration_for_default_null_value' => false,
'no_superfluous_phpdoc_tags' => [
'allow_mixed' => true,
'no_superfluous_phpdoc_tags' => [
'allow_mixed' => true,
'allow_unused_params' => false,
'remove_inheritdoc' => false,
],
'no_null_property_initialization' => false,
])
Expand Down
103 changes: 103 additions & 0 deletions src/Bean/Util/AttributeUtil.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
<?php

declare(strict_types=1);

namespace Imi\Bean\Util;

use Imi\Util\Traits\TStaticClass;

class AttributeUtil
{
use TStaticClass;

public static function generateAttributesCode(object|array $attributes, int $level = 0): string
{
$attributeCodes = [];
$tab1 = str_repeat(' ', $level + 1);
$tab2 = str_repeat(' ', $level + 2);
foreach (\is_array($attributes) ? $attributes : [$attributes] as $attribute)
{
$ref = new \ReflectionClass($attribute);
if (!$ref->getAttributes(\Attribute::class))
{
throw new \InvalidArgumentException(sprintf('Class %s does not an Attribute', $ref->name));
}
$constructor = $ref->getConstructor();
$props = [];
foreach ($attribute as $key => $value)
{
if ($ref->hasProperty($key))
{
$prop = $ref->getProperty($key);
if ($prop->hasDefaultValue())
{
if ($prop->getDefaultValue() === $value)
{
continue;
}
}
}
// 构造方法属性提升,无法获取到属性默认值,所以需要获取构造方法参数处理
if ($constructor)
{
foreach ($constructor->getParameters() as $param)
{
if ($param->name === $key)
{
if ($param->isDefaultValueAvailable() && $param->getDefaultValue() === $value)
{
continue 2;
}
break;
}
}
}
if (\is_object($value))
{
$value = self::generateAttributesCode([$value], $level + 1);
}
elseif (\is_array($value))
{
$newValue = [];
foreach ($value as $itemKey => $itemValue)
{
if (\is_object($itemValue))
{
$newValue[$itemKey] = self::generateAttributesCode($itemValue, $level + 1);
}
else
{
$newValue[$itemKey] = $tab2 . var_export($itemValue, true);
}
}
$value = '[' . \PHP_EOL . implode(',' . \PHP_EOL, $newValue) . \PHP_EOL . $tab1 . ']';
}
else
{
$value = var_export($value, true);
}
$props[] = $key . ': ' . $value;
}
$attributeCodes[] = $tab1 . ($level ? 'new ' : '') . '\\' . $ref->name . '(' . implode(', ', $props) . ')';
}

$result = implode(',' . \PHP_EOL, $attributeCodes);
if (\is_object($attributes))
{
if (0 === $level)
{
$result = '#[' . \PHP_EOL . $result . \PHP_EOL . str_repeat(' ', $level) . ']';
}
}
else
{
$result = '[' . \PHP_EOL . $result . \PHP_EOL . str_repeat(' ', $level) . ']';
if (0 === $level)
{
$result = '#' . $result;
}
}

return $result;
}
}
6 changes: 3 additions & 3 deletions src/Components/jwt/src/Facade/JWT.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,9 @@

namespace Imi\JWT\Facade;

use Imi\Facade\Annotation\Facade;
use Imi\Facade\BaseFacade;

/**
* @Facade(class="JWT", request=false, args={})
*
* @method static void __init()
* @method static \Imi\JWT\Model\JWTConfig[] getList()
* @method static string|null getDefault()
Expand All @@ -21,6 +18,9 @@
* @method static void validate(?string $name, \Lcobucci\JWT\Token $token)
* @method static int getJwtPackageVersion()
*/
#[
\Imi\Facade\Annotation\Facade(class: 'JWT')
]
class JWT extends BaseFacade
{
}
11 changes: 10 additions & 1 deletion src/Components/pgsql/src/Model/Cli/Model/ModelGenerate.php
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,11 @@ public function generate(string $namespace, string $baseClass, ?string $database
}
$this->parseFields($poolName, $fields, $data, 'v' === $item['relkind'], $table, $typeDefinitions);

$data['classAttributeCode'] = \Imi\Bean\Util\AttributeUtil::generateAttributesCode([
new \Imi\Model\Annotation\Entity(camel: $data['entity'], bean: $data['bean'], incrUpdate: $data['incrUpdate']),
new \Imi\Model\Annotation\Table(name: $data['table']['name'], usePrefix: $data['table']['usePrefix'], id: $data['table']['id'], dbPoolName: $data['poolName']),
]);

$baseFileName = File::path($basePath, $className . 'Base.php');
if (!is_file($baseFileName) || true === $override || 'base' === $override)
{
Expand Down Expand Up @@ -304,7 +309,7 @@ private function parseFields(?string $poolName, array $fields, ?array &$data, bo

$isPk = $field['ordinal_position'] > 0;
[$phpType, $phpDefinitionType, $typeConvert] = $this->dbFieldTypeToPhp($field);
$data['fields'][] = [
$fieldData = [
'name' => $field['attname'],
'varName' => Text::toCamelName($field['attname']),
'type' => $type = ('_' === $field['typname'][0] ? substr((string) $field['typname'], 1) : $field['typname']),
Expand All @@ -325,6 +330,10 @@ private function parseFields(?string $poolName, array $fields, ?array &$data, bo
'ref' => \in_array($type, ['json', 'jsonb']),
'virtual' => 's' === $field['attgenerated'],
];
$fieldData['attributesCode'] = \Imi\Bean\Util\AttributeUtil::generateAttributesCode([
new \Imi\Model\Annotation\Column(name: $fieldData['name'], type: $fieldData['type'], length: $fieldData['length'], accuracy: $fieldData['accuracy'], nullable: $fieldData['nullable'], default: $fieldData['default'], isPrimaryKey: $fieldData['isPrimaryKey'], primaryKeyIndex: $fieldData['primaryKeyIndex'], isAutoIncrement: $fieldData['isAutoIncrement'], ndims: $fieldData['ndims'], virtual: $fieldData['virtual']),
]);
$data['fields'][] = $fieldData;
if ($isPk)
{
$data['table']['id'][$primaryKeyIndex] = $field['attname'];
Expand Down
19 changes: 6 additions & 13 deletions src/Components/pgsql/src/Model/Cli/Model/base-template.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,21 @@ declare(strict_types=1);

namespace <?php echo $namespace; ?>\Base;

use Imi\Model\Annotation\Column;
use Imi\Model\Annotation\Entity;
use Imi\Model\Annotation\Table;
use <?php echo $baseClassName; ?> as Model;

/**
* <?php echo $tableComment; ?> 基类.
*
* @Entity(camel=<?php echo var_export($entity, true); ?>, bean=<?php echo var_export($bean, true); ?>, incrUpdate=<?php echo var_export($incrUpdate, true); ?>)
* @Table(name="<?php echo $table['name']; ?>", usePrefix=<?php var_export($table['usePrefix']); ?><?php if (isset($table['id'][0]))
{ ?>, id={<?php echo '"', implode('", "', $table['id']), '"'; ?>}<?php } ?>, dbPoolName=<?php if (null === $poolName)
{ ?>null<?php }
else
{
echo '"', $poolName, '"';
}?>)
* 此文件是自动生成,请勿手动修改此文件!
*
<?php foreach ($fields as $field)
{ ?>
* @property <?php echo $field['phpType']; ?> $<?php echo $field['varName']; ?> <?php echo '' === $field['comment'] ? '' : $field['comment']; ?>
<?php } ?>
*/
<?php echo $classAttributeCode; ?>

abstract class <?php echo $className; ?>Base extends Model
{
/**
Expand Down Expand Up @@ -56,10 +48,11 @@ else
* <?php echo $field['name']; ?>
<?php } ?>
* @Column(name="<?php echo $field['name']; ?>", type="<?php echo $field['type']; ?>", length=<?php echo $field['length']; ?>, accuracy=<?php echo $field['accuracy']; ?>, nullable=<?php echo json_encode($field['nullable']); ?>, default="<?php echo $field['default']; ?>", isPrimaryKey=<?php echo json_encode($field['isPrimaryKey']); ?>, primaryKeyIndex=<?php echo $field['primaryKeyIndex']; ?>, isAutoIncrement=<?php echo json_encode($field['isAutoIncrement']); ?>, ndims=<?php echo $field['ndims']; ?>, virtual=<?php var_export($field['virtual']); ?>)
* @var <?php echo $field['phpType']; ?>

*/
<?php echo $field['attributesCode']; ?>

protected <?php if ($field['typeDefinition'] && $field['phpDefinitionType'])
{ ?><?php echo $field['phpDefinitionType']; ?> <?php } ?>$<?php echo $field['varName']; ?> = <?php var_export($field['defaultValue']); ?>;

Expand All @@ -84,7 +77,7 @@ else

* @return static
*/
public function set<?php echo ucfirst($field['varName']); ?>($<?php echo $field['varName']; ?>)
public function set<?php echo ucfirst($field['varName']); ?>(mixed $<?php echo $field['varName']; ?>): self
{
<?php if ($lengthCheck && 0 === $field['ndims'] && $length = [
'character' => $field['length'],
Expand Down
3 changes: 1 addition & 2 deletions src/Components/pgsql/src/Model/Cli/Model/template.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@ use <?php echo $namespace; ?>\Base\<?php echo $className; ?>Base;

/**
* <?php echo $tableComment; ?>.
*
* @Inherit
*/
#[Inherit]
class <?php echo $className; ?> extends <?php echo $className; ?>Base
{
Expand Down
34 changes: 19 additions & 15 deletions src/Components/pgsql/tests/Model/Base/ArrayTestBase.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,23 @@

namespace Imi\Pgsql\Test\Model\Base;

use Imi\Model\Annotation\Column;
use Imi\Model\Annotation\Entity;
use Imi\Model\Annotation\Table;
use Imi\Pgsql\Model\PgModel as Model;

/**
* tb_array_test 基类.
*
* @Entity(camel=true, bean=true, incrUpdate=false)
*
* @Table(name="tb_array_test", usePrefix=false, id={"id"}, dbPoolName=null)
* 此文件是自动生成,请勿手动修改此文件!
*
* @property int|null $id
* @property array<int>|null $arr1
* @property array<array<string>>|null $arr2
*/
#[
\Imi\Model\Annotation\Entity(),
\Imi\Model\Annotation\Table(name: 'tb_array_test', id: [
'id',
])
]
abstract class ArrayTestBase extends Model
{
/**
Expand All @@ -34,9 +35,10 @@ abstract class ArrayTestBase extends Model

/**
* id.
*
* @Column(name="id", type="int4", length=-1, accuracy=0, nullable=false, default="", isPrimaryKey=true, primaryKeyIndex=0, isAutoIncrement=true, ndims=0, virtual=false)
*/
#[
\Imi\Model\Annotation\Column(name: 'id', type: 'int4', nullable: false, isPrimaryKey: true, primaryKeyIndex: 0, isAutoIncrement: true)
]
protected ?int $id = null;

/**
Expand All @@ -54,7 +56,7 @@ public function getId(): ?int
*
* @return static
*/
public function setId($id)
public function setId(mixed $id): self
{
$this->id = null === $id ? null : (int) $id;

Expand All @@ -64,10 +66,11 @@ public function setId($id)
/**
* arr1.
*
* @Column(name="arr1", type="int8", length=-1, accuracy=0, nullable=false, default="", isPrimaryKey=false, primaryKeyIndex=-1, isAutoIncrement=false, ndims=1, virtual=false)
*
* @var array<int>|null
*/
#[
\Imi\Model\Annotation\Column(name: 'arr1', type: 'int8', nullable: false, ndims: 1)
]
protected ?array $arr1 = null;

/**
Expand All @@ -87,7 +90,7 @@ public function getArr1(): ?array
*
* @return static
*/
public function setArr1($arr1)
public function setArr1(mixed $arr1): self
{
$this->arr1 = null === $arr1 ? null : $arr1;

Expand All @@ -97,10 +100,11 @@ public function setArr1($arr1)
/**
* arr2.
*
* @Column(name="arr2", type="varchar", length=255, accuracy=0, nullable=false, default="", isPrimaryKey=false, primaryKeyIndex=-1, isAutoIncrement=false, ndims=2, virtual=false)
*
* @var array<array<string>>|null
*/
#[
\Imi\Model\Annotation\Column(name: 'arr2', type: 'varchar', length: 255, nullable: false, ndims: 2)
]
protected ?array $arr2 = null;

/**
Expand All @@ -120,7 +124,7 @@ public function getArr2(): ?array
*
* @return static
*/
public function setArr2($arr2)
public function setArr2(mixed $arr2): self
{
$this->arr2 = null === $arr2 ? null : $arr2;

Expand Down
Loading

0 comments on commit e32aeab

Please sign in to comment.