1: <?php declare( strict_types = 1 );
2:
3: namespace Waves\Model;
4:
5: use Exception;
6: use Waves\Common\ExceptionCode;
7:
8: class Alias
9: {
10: const PREFIX = 'alias:';
11: const MIN_LENGTH = 4;
12: const MAX_LENGTH = 30;
13: const BYTES_LENGTH = 1 + 1 + Alias::MAX_LENGTH;
14:
15: const ALPHABET = '-.0-9@_a-z';
16: const MATCH = '/[' . Alias::ALPHABET . ']{' . Alias::MIN_LENGTH . ',' . Alias::MAX_LENGTH . '}/';
17:
18: private string $name;
19: private string $fullAlias;
20:
21: private function __construct( string $alias, ChainId $chainId = null )
22: {
23: $matches = [];
24: preg_match( Alias::MATCH, $alias, $matches );
25: if( !isset( $matches[0] ) || $matches[0] !== $alias )
26: throw new Exception( __FUNCTION__ . ' bad alias name = `' . serialize( $alias ) . '`', ExceptionCode::BAD_ALIAS );
27: if( !isset( $chainId ) )
28: $chainId = WavesConfig::chainId();
29: $this->name = $alias;
30: $this->fullAlias = Alias::PREFIX . $chainId->asString() . ':' . $alias;
31: }
32:
33: static function fromString( string $alias, ChainId $chainId = null ): Alias
34: {
35: return new Alias( $alias, $chainId );
36: }
37:
38: static function fromFullAlias( string $fullAlias ): Alias
39: {
40: if( strlen( $fullAlias ) >= 12 )
41: {
42: $prefix = substr( $fullAlias, 0, strlen( Alias::PREFIX ) );
43: if( $prefix === Alias::PREFIX && $fullAlias[7] === ':' )
44: {
45: $chainId = ChainId::fromString( $fullAlias[6] );
46: $alias = substr( $fullAlias, 8 );
47: return new Alias( $alias, $chainId );
48: }
49: }
50:
51: throw new Exception( __FUNCTION__ . ' bad alias name = `' . serialize( $fullAlias ) . '`', ExceptionCode::BAD_ALIAS );
52: }
53:
54: static function isValid( string $alias, ChainId $chainId = null ): bool
55: {
56: return $alias === (new Alias( $alias, $chainId ))->name();
57: }
58:
59: function chainId(): ChainId
60: {
61: return ChainId::fromString( $this->fullAlias[6] );
62: }
63:
64: function name(): string
65: {
66: return $this->name;
67: }
68:
69: function toString(): string
70: {
71: return $this->fullAlias;
72: }
73: }
74: