You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.6 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Helper;
use App\Exception\BusinessException;
use Hyperf\Database\Model\Relations\Relation;
class Morph
{
/**
* 只支持多态关联实体的关联键为id
*
* @param int $morphId
* @param string $morphType
* @return void
*/
public static function getMorph(int $morphId, string $morphType)
{
$class = self::getMorphClass($morphType);
if (is_null($class)) {
throw new BusinessException('Morph type error!');
}
return $class::where('id', $morphId)->first();
}
public static function getMorphClass(string $morphType): ?string
{
return Relation::$morphMap[$morphType] ?? null;
}
/**
* 验证评论类型是否存在
*
* @param string $morphType
* @return void
* @throws BusinessException
*/
public static function checkMorphType(string $morphType)
{
if (is_null(self::getMorphClass($morphType))) {
throw new BusinessException('Morph type error!');
}
}
public static function instanceOf(string $morphType, $instance): bool
{
return get_class($instance) === self::getMorphClass($morphType);
}
public static function getMorphTypeOfInstance(object $instance): string
{
return self::getMorphType(get_class($instance));
}
public static function getMorphType(string $class): string
{
$morphMap = Relation::$morphMap;
$morphMap = array_flip($morphMap);
return $morphMap[$class] ?? '';
}
}