@@ -62,6 +62,18 @@ public static function fromString(string $toml): self
6262 return new self (self ::parseProfiles ($ data ['profile ' ] ?? []));
6363 }
6464
65+ /**
66+ * Convert the configuration back to TOML string.
67+ *
68+ * @return string TOML representation of the configuration
69+ */
70+ public function toToml (): string
71+ {
72+ return (string ) Toml::encode ([
73+ 'profile ' => \array_map (self ::encodeProfile (...), $ this ->profiles ),
74+ ]);
75+ }
76+
6577 /**
6678 * Assert a condition and throw an exception if it fails.
6779 *
@@ -173,4 +185,48 @@ private static function parseCodec(array $codec): ?ConfigCodec
173185 auth: $ auth ,
174186 );
175187 }
188+
189+ private static function encodeProfile (ConfigProfile $ profile ): array
190+ {
191+ $ result = [];
192+ $ profile ->address === null or $ result ['address ' ] = $ profile ->address ;
193+ $ profile ->namespace === null or $ result ['namespace ' ] = $ profile ->namespace ;
194+ $ profile ->apiKey === null or $ result ['api_key ' ] = (string ) $ profile ->apiKey ;
195+ $ profile ->tlsConfig === null or $ result ['tls ' ] = self ::encodeTls ($ profile ->tlsConfig );
196+ $ profile ->grpcMeta === [] or $ result ['grpc_meta ' ] = $ profile ->grpcMeta ;
197+ $ profile ->codecConfig === null or $ result ['codec ' ] = self ::encodeCodec ($ profile ->codecConfig );
198+ return $ result ;
199+ }
200+
201+ private static function encodeTls (ConfigTls $ config ): array
202+ {
203+ $ result = [];
204+ $ config ->disabled === null or $ result ['disabled ' ] = $ config ->disabled ;
205+ $ config ->rootCerts === null or self ::isCertFile ($ config ->rootCerts )
206+ ? $ result ['server_ca_cert_path ' ] = $ config ->rootCerts
207+ : $ result ['server_ca_cert_data ' ] = $ config ->rootCerts ;
208+ $ config ->privateKey === null or self ::isCertFile ($ config ->privateKey )
209+ ? $ result ['client_key_path ' ] = $ config ->privateKey
210+ : $ result ['client_key_data ' ] = $ config ->privateKey ;
211+ $ config ->certChain === null or self ::isCertFile ($ config ->certChain )
212+ ? $ result ['client_cert_path ' ] = $ config ->certChain
213+ : $ result ['client_cert_data ' ] = $ config ->certChain ;
214+ $ config ->serverName === null or $ result ['server_name ' ] = $ config ->serverName ;
215+ return $ result ;
216+ }
217+
218+ private static function isCertFile (string $ certOrPath ): bool
219+ {
220+ return \str_starts_with ($ certOrPath , '/ ' )
221+ || \str_starts_with ($ certOrPath , './ ' )
222+ || \str_starts_with ($ certOrPath , '../ ' );
223+ }
224+
225+ private static function encodeCodec (ConfigCodec $ config ): array
226+ {
227+ $ result = [];
228+ $ config ->endpoint === null or $ result ['endpoint ' ] = $ config ->endpoint ;
229+ $ config ->auth === null or $ result ['auth ' ] = $ config ->auth ;
230+ return $ result ;
231+ }
176232}
0 commit comments