Entitas  0.40.0
Entitas is a super fast Entity Component System (ECS) Framework specifically made for C# and Unity
Properties.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text.RegularExpressions;
5 
6 namespace Entitas {
7 
8  public class Properties {
9 
10  public string[] keys { get { return _dict.Keys.ToArray(); } }
11  public string[] values { get { return _dict.Values.ToArray(); } }
12 
13  public int count { get { return _dict.Count; } }
14 
15  public string this[string key] {
16  get { return _dict[key]; }
17  set {
18  _dict[key.Trim()] = value
19  .TrimStart()
20  .Replace("\\n", "\n")
21  .Replace("\\t", "\t");
22  }
23  }
24 
25  readonly Dictionary<string, string> _dict;
26 
27  public Properties() : this(string.Empty) {
28  }
29 
30  public Properties(string properties) {
31  properties = convertLineEndings(properties);
32  _dict = new Dictionary<string, string>();
33  var lines = getLinesWithProperties(properties);
34  addProperties(mergeMultilineValues(lines));
35  replacePlaceholders();
36  }
37 
38  public bool HasKey(string key) {
39  return _dict.ContainsKey(key);
40  }
41 
42  static string convertLineEndings(string str) {
43  return str.Replace("\r\n", "\n").Replace("\r", "\n");
44  }
45 
46  static string[] getLinesWithProperties(string properties) {
47  var delimiter = new[] { '\n' };
48  return properties
49  .Split(delimiter, StringSplitOptions.RemoveEmptyEntries)
50  .Select(line => line.TrimStart(' '))
51  .Where(line => !line.StartsWith("#", StringComparison.Ordinal))
52  .ToArray();
53  }
54 
55  static string[] mergeMultilineValues(string[] lines) {
56  var currentProperty = string.Empty;
57  return lines.Aggregate(new List<string>(), (acc, line) => {
58  currentProperty += line;
59  if(currentProperty.EndsWith("\\", StringComparison.Ordinal)) {
60  currentProperty = currentProperty.Substring(
61  0, currentProperty.Length - 1
62  );
63  } else {
64  acc.Add(currentProperty);
65  currentProperty = string.Empty;
66  }
67 
68  return acc;
69  }).ToArray();
70  }
71 
72  void addProperties(string[] lines) {
73  var keyValueDelimiter = new[] { '=' };
74  var properties = lines.Select(
75  line => line.Split(keyValueDelimiter, 2)
76  );
77  foreach(var property in properties) {
78  this[property[0]] = property[1];
79  }
80  }
81 
82  void replacePlaceholders() {
83  const string placeholderPattern = @"(?:(?<=\${).+?(?=}))";
84  foreach(var key in _dict.Keys.ToArray()) {
85  var matches = Regex.Matches(_dict[key], placeholderPattern);
86  foreach(Match match in matches) {
87  _dict[key] = _dict[key].Replace(
88  "${" + match.Value + "}", _dict[match.Value]
89  );
90  }
91  }
92  }
93 
94  public override string ToString() {
95  return _dict.Aggregate(string.Empty, (properties, kv) => {
96  var content = kv.Value
97  .Replace("\n", "\\n")
98  .Replace("\t", "\\t");
99 
100  return properties + kv.Key + " = " + content + "\n";
101  });
102  }
103  }
104 }