75 lines
2.1 KiB
PHP
75 lines
2.1 KiB
PHP
<?php
|
|
|
|
namespace app\common\service;
|
|
|
|
use app\common\validate\VehDictI18nValidate;
|
|
use app\common\traits\crud\CrudServiceTrait;
|
|
use app\common\model\VehDictI18n;
|
|
|
|
class VehDictI18nService
|
|
{
|
|
|
|
use CrudServiceTrait;
|
|
|
|
/**
|
|
* 指定当前要操作的模型
|
|
*/
|
|
protected string $modelClass = VehDictI18n::class;
|
|
|
|
/**
|
|
* 验证器
|
|
*/
|
|
protected $validator = VehDictI18nValidate::class;
|
|
|
|
/**
|
|
* 获取验证器
|
|
*/
|
|
public function getValidator()
|
|
{
|
|
return new $this->validator;
|
|
}
|
|
|
|
|
|
/** 本进程缓存:[dict][code] => labels array */
|
|
protected static array $labelsCache = [];
|
|
|
|
public static function label(string $dict=null, ?string $code=null, string $locale='zh-CN', ?string $fallbackZh=null): ?string
|
|
{
|
|
if (!$dict || !$code) return $fallbackZh;
|
|
|
|
$labels = self::labels($dict, $code);
|
|
if (!$labels) return $fallbackZh ?? $code;
|
|
|
|
return $labels[$locale] ?? $labels['zh-CN'] ?? $code;
|
|
}
|
|
|
|
/** 返回 labels 数组,命中缓存 */
|
|
public static function labels(string $dict, string $code): ?array
|
|
{
|
|
$dict = strtoupper($dict);
|
|
$code = (string)$code;
|
|
|
|
if (isset(self::$labelsCache[$dict][$code])) {
|
|
return self::$labelsCache[$dict][$code];
|
|
}
|
|
|
|
$term = DictTerm::where('dict',$dict)->where('code',$code)->first(['labels']);
|
|
if (!$term) return null;
|
|
|
|
$labels = $term->labels ?? null;
|
|
if (!is_array($labels)) return null;
|
|
|
|
self::$labelsCache[$dict][$code] = $labels;
|
|
return $labels;
|
|
}
|
|
|
|
/** 校验 code 是否存在于字典(用于必填维度) */
|
|
public static function ensureExists(string $dict, ?string $code, string $fieldNameForError): void
|
|
{
|
|
if ($code === null || $code === '') {
|
|
throw new \InvalidArgumentException("缺少必填字段:{$fieldNameForError}");
|
|
}
|
|
$ok = VehDictI18n::where('dict',$dict)->where('code',$code)->where('status', 1)->exists();
|
|
if (!$ok) throw new \InvalidArgumentException("字典不存在或未启用:{$dict}.{$code}");
|
|
}
|
|
} |