|
| 1 | +using JetBrains.Annotations; |
| 2 | +using SER.Code.ArgumentSystem.Arguments; |
| 3 | +using SER.Code.ArgumentSystem.BaseArguments; |
| 4 | +using SER.Code.Exceptions; |
| 5 | +using SER.Code.Helpers.ResultSystem; |
| 6 | +using SER.Code.MethodSystem.BaseMethods.Synchronous; |
| 7 | +using SER.Code.ValueSystem; |
| 8 | +using SER.Code.ValueSystem.PropertySystem; |
| 9 | +using System; |
| 10 | +using System.Linq; |
| 11 | + |
| 12 | +namespace SER.Code.MethodSystem.Methods.PropertyMethods; |
| 13 | + |
| 14 | +[UsedImplicitly] |
| 15 | +public class SetPropertyMethod : SynchronousMethod |
| 16 | +{ |
| 17 | + public override string Description => "Sets a property of a reference object."; |
| 18 | + |
| 19 | + public override Argument[] ExpectedArguments { get; } = |
| 20 | + [ |
| 21 | + new LooseReferenceArgument("object", typeof(object)), |
| 22 | + new TextArgument("property name", false), |
| 23 | + new AnyValueArgument("value") |
| 24 | + ]; |
| 25 | + |
| 26 | + public override void Execute() |
| 27 | + { |
| 28 | + var target = Args.GetLooseReference<object>("object"); |
| 29 | + var propertyName = Args.GetText("property name"); |
| 30 | + var newValue = Args.GetAnyValue("value"); |
| 31 | + |
| 32 | + if (target == null) |
| 33 | + throw new ScriptRuntimeError(this, "Target object is null."); |
| 34 | + |
| 35 | + var props = ReferencePropertyRegistry.GetProperties(target.GetType()); |
| 36 | + if (!props.TryGetValue(propertyName, out var propInfo)) |
| 37 | + { |
| 38 | + var writableProps = props |
| 39 | + .Where(p => p.Value.IsSettable) |
| 40 | + .Select(p => p.Key) |
| 41 | + .OrderBy(n => n) |
| 42 | + .ToArray(); |
| 43 | + |
| 44 | + var msg = $"Property '{propertyName}' not found on object of type '{target.GetType().Name}'."; |
| 45 | + if (writableProps.Length > 0) |
| 46 | + { |
| 47 | + msg += $" Available writable properties: {string.Join(", ", writableProps)}"; |
| 48 | + } |
| 49 | + else |
| 50 | + { |
| 51 | + msg += " This object has no writable properties."; |
| 52 | + } |
| 53 | + throw new ScriptRuntimeError(this, msg); |
| 54 | + } |
| 55 | + |
| 56 | + if (!propInfo.IsSettable) |
| 57 | + { |
| 58 | + var writableProps = props |
| 59 | + .Where(p => p.Value.IsSettable) |
| 60 | + .Select(p => p.Key) |
| 61 | + .OrderBy(n => n) |
| 62 | + .ToArray(); |
| 63 | + |
| 64 | + var msg = $"Property '{propertyName}' is read-only."; |
| 65 | + if (writableProps.Length > 0) |
| 66 | + { |
| 67 | + msg += $" Available writable properties: {string.Join(", ", writableProps)}"; |
| 68 | + } |
| 69 | + throw new ScriptRuntimeError(this, msg); |
| 70 | + } |
| 71 | + |
| 72 | + var result = propInfo.SetValue(target, newValue); |
| 73 | + if (result.HasErrored(out var error)) |
| 74 | + { |
| 75 | + throw new ScriptRuntimeError(this, $"Failed to set property '{propertyName}': {error}"); |
| 76 | + } |
| 77 | + } |
| 78 | +} |
0 commit comments