1: <?php declare( strict_types = 1 );
2:
3: namespace Waves\Common;
4:
5: use Exception;
6:
7: class Base64String
8: {
9: const PROLOG = 'base64:';
10: private string $bytes;
11: private string $encoded;
12:
13: private function __construct(){}
14:
15: static function emptyString(): Base64String
16: {
17: $base64String = new Base64String;
18: $base64String->bytes = '';
19: $base64String->encoded = '';
20: return $base64String;
21: }
22:
23: static function fromString( string $encoded ): Base64String
24: {
25: if( substr( $encoded, 0, 7 ) === Base64String::PROLOG )
26: $encoded = substr( $encoded, 7 );
27:
28: $base64String = new Base64String;
29: $base64String->encoded = $encoded;
30: return $base64String;
31: }
32:
33: static function fromBytes( string $bytes ): Base64String
34: {
35: $base64String = new Base64String;
36: $base64String->bytes = $bytes;
37: return $base64String;
38: }
39:
40: function bytes(): string
41: {
42: if( !isset( $this->bytes ) )
43: {
44: $this->bytes = base64_decode( $this->encoded );
45: if( !is_string( $this->bytes ) )
46: throw new Exception( __FUNCTION__ . ' failed to decode string: ' . $this->encoded, ExceptionCode::BASE64_DECODE );
47: }
48: return $this->bytes;
49: }
50:
51: function encoded(): string
52: {
53: if( !isset( $this->encoded ) )
54: $this->encoded = base64_encode( $this->bytes );
55: return $this->encoded;
56: }
57:
58: function encodedWithPrefix(): string
59: {
60: return Base64String::PROLOG . $this->encoded();
61: }
62:
63: function toString(): string
64: {
65: return $this->encodedWithPrefix();
66: }
67:
68: /**
69: * @return string|null
70: */
71: function toJsonValue()
72: {
73: if( $this->bytes() === '' )
74: return null;
75: return $this->encodedWithPrefix();
76: }
77: }
78: