Skip to content

Commit

Permalink
Added Annotation RewriteReturnType which used to rewrite the return…
Browse files Browse the repository at this point in the history
… type when generating models.
  • Loading branch information
limingxinleo committed Dec 28, 2023
1 parent f4033ca commit 10ef79b
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
23 changes: 23 additions & 0 deletions src/Commands/Annotations/RewriteReturnType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\Database\Commands\Annotations;

use Attribute;
use Hyperf\Di\Annotation\AbstractAnnotation;

#[Attribute(Attribute::TARGET_METHOD)]
class RewriteReturnType extends AbstractAnnotation
{
public function __construct(public string $type)
{
}
}
15 changes: 14 additions & 1 deletion src/Commands/Ast/ModelUpdateVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Hyperf\Contract\Castable;
use Hyperf\Contract\CastsAttributes;
use Hyperf\Contract\CastsInboundAttributes;
use Hyperf\Database\Commands\Annotations\RewriteReturnType;
use Hyperf\Database\Commands\ModelOption;
use Hyperf\Database\Model\Collection;
use Hyperf\Database\Model\Model;
Expand Down Expand Up @@ -280,9 +281,21 @@ protected function initPropertiesFromMethods()
if (is_subclass_of($caster, CastsAttributes::class)) {
$ref = new ReflectionClass($caster);
$method = $ref->getMethod('get');
$annotations = $method->getAttributes(RewriteReturnType::class);
/** @var RewriteReturnType $annotation */
if (isset($annotations[0]) && $annotation = $annotations[0]->newInstance()) {
$this->setProperty($key, [$annotation->type], true, true, '', false);
continue;
}

if ($type = $method->getReturnType()) {
$typeName = '\\' . ltrim($type->getName(), '\\');
// TODO: Support after some days.
// if (PhpDocReader::getInstance()->isPrimitiveType($typeName)) {
// $typeName = $type->getName();
// }
// Get return type which defined in `CastsAttributes::get()`.
$this->setProperty($key, ['\\' . ltrim($type->getName(), '\\')], true, true, '', true);
$this->setProperty($key, [$typeName], true, true, '', true);
}
}
}
Expand Down

0 comments on commit 10ef79b

Please sign in to comment.