1+ using System ;
2+ using System . IO ;
3+ using Microsoft . Extensions . Configuration . Json ;
4+ using Newtonsoft . Json ;
5+ using Newtonsoft . Json . Linq ;
6+
7+ namespace SimpleStateMachineNodeEditor . Helpers . Configuration
8+ {
9+ public class WritableJsonConfigurationProvider : JsonConfigurationProvider
10+ {
11+ public WritableJsonConfigurationProvider ( JsonConfigurationSource source ) : base ( source )
12+ {
13+ }
14+
15+ private void Save ( dynamic jsonObj )
16+ {
17+ var fileFullPath = base . Source . FileProvider . GetFileInfo ( base . Source . Path ) . PhysicalPath ;
18+ string output = JsonConvert . SerializeObject ( jsonObj , Formatting . Indented ) ;
19+ File . WriteAllText ( fileFullPath , output ) ;
20+ }
21+
22+ private void SetValue ( string key , string value , dynamic jsonObj )
23+ {
24+ base . Set ( key , value ) ;
25+ var split = key . Split ( ":" ) ;
26+ var context = jsonObj ;
27+ for ( int i = 0 ; i < split . Length ; i ++ )
28+ {
29+ var currentKey = split [ i ] ;
30+ if ( i < split . Length - 1 )
31+ {
32+ var child = jsonObj [ currentKey ] ;
33+ if ( child == null )
34+ {
35+ context [ currentKey ] = new JObject ( ) ;
36+ }
37+ context = context [ currentKey ] ;
38+ }
39+ else
40+ {
41+ context [ currentKey ] = value ;
42+ }
43+ }
44+ }
45+
46+ private dynamic GetJsonObj ( )
47+ {
48+ var fileFullPath = base . Source . FileProvider . GetFileInfo ( base . Source . Path ) . PhysicalPath ;
49+ var json = File . Exists ( fileFullPath ) ? File . ReadAllText ( fileFullPath ) : "{}" ;
50+ return JsonConvert . DeserializeObject ( json ) ;
51+ }
52+
53+ public override void Set ( string key , string value )
54+ {
55+ var jsonObj = GetJsonObj ( ) ;
56+ SetValue ( key , value , jsonObj ) ;
57+ Save ( jsonObj ) ;
58+ }
59+
60+ public void Set ( string key , object value )
61+ {
62+ var jsonObj = GetJsonObj ( ) ;
63+ var serialized = JsonConvert . SerializeObject ( value ) ;
64+ var jToken = JsonConvert . DeserializeObject ( serialized ) as JToken ?? new JValue ( value ) ;
65+ WalkAndSet ( key , jToken , jsonObj ) ;
66+ Save ( jsonObj ) ;
67+ }
68+
69+ private void WalkAndSet ( string key , JToken value , dynamic jsonObj )
70+ {
71+ switch ( value )
72+ {
73+ case JArray jArray :
74+ {
75+ //TODO Realize arrays
76+ break ;
77+ }
78+ case JObject jObject :
79+ {
80+ foreach ( var propertyInfo in jObject . Properties ( ) )
81+ {
82+ var propName = propertyInfo . Name ;
83+ var currentKey = key == null ? propName : $ "{ key } :{ propName } ";
84+ var propValue = propertyInfo . Value ;
85+ WalkAndSet ( currentKey , propValue , jsonObj ) ;
86+ }
87+ break ;
88+ }
89+ case JValue jValue :
90+ {
91+ SetValue ( key , jValue . ToString ( ) , jsonObj ) ;
92+ break ;
93+ }
94+ default :
95+ throw new ArgumentOutOfRangeException ( nameof ( value ) ) ;
96+ }
97+ }
98+ }
99+ }
0 commit comments