<?php if(!defined('PRIVATE_DIR'))exit; class PublicId{ private static array $entities=['store'=>'st','faq'=>'fq','review'=>'rv','product'=>'pd','order'=>'or','user'=>'us','ticket'=>'tk','category'=>'ct','block'=>'bk','campaign'=>'cm']; public static function get(string $entityType,int $internalId):string{ self::validateType($entityType); $existing=Database::fetchOne("SELECT public_id FROM public_ids WHERE entity_type=:t AND internal_id=:id",[':t'=>$entityType,':id'=>$internalId]); if($existing)return $existing['public_id']; return self::generate($entityType,$internalId); } public static function generate(string $entityType,int $internalId):string{ self::validateType($entityType); $publicId=self::createUniqueId(); Database::execute("INSERT INTO public_ids (entity_type,internal_id,public_id,created_at) VALUES (:t,:id,:pid,NOW()) ON DUPLICATE KEY UPDATE public_id=VALUES(public_id)",[':t'=>$entityType,':id'=>$internalId,':pid'=>$publicId]); return $publicId; } public static function resolve(string $entityType,string $publicId):?int{ self::validateType($entityType); $prefix=self::$entities[$entityType]??''; if($prefix&&strpos($publicId,$prefix.'_')===0){$publicId=substr($publicId,strlen($prefix)+1);} $row=Database::fetchOne("SELECT internal_id FROM public_ids WHERE entity_type=:t AND public_id=:pid",[':t'=>$entityType,':pid'=>$publicId]); return $row?(int)$row['internal_id']:null; } public static function display(string $entityType,int $internalId):string{ $prefix=self::$entities[$entityType]??''; $pubId=self::get($entityType,$internalId); return $prefix?$prefix.'_'.$pubId:$pubId; } public static function getBatch(string $entityType,array $internalIds):array{ self::validateType($entityType); $map=[]; foreach($internalIds as $id){$map[(int)$id]=self::get($entityType,(int)$id);} return $map; } private static function createUniqueId():string{ $chars='0123456789abcdefghijklmnopqrstuvwxyz'; $id='';$bytes=random_bytes(10); for($i=0;$i<10;$i++){$id.=$chars[ord($bytes[$i])%36];} return $id; } private static function validateType(string $type):void{ if(!isset(self::$entities[$type]))throw new \InvalidArgumentException("Unknown entity type: {$type}"); } public static function prefix(string $entityType):string{return self::$entities[$entityType]??'';} } 