Beispiel #1
0
        /// <summary>
        /// Attempts to convert the arguments provided into objects of types required by the command executor
        /// </summary>
        /// <param name="ctx"></param>
        protected override void ConvertArgumentsToTypes(IContextObject ctx)
        {
            Objects = new List <object> {
                ctx
            };
            int index = 0;
            IEnumerable <object> arguments = Input.ObjectiveExplode();

            if (AdditionalArgs != null)
            {
                arguments = arguments.Concat(AdditionalArgs);
            }

            foreach (KeyValuePair <ParameterInfo, CommandParameterAttribute> kvp in ExecutorData.ParameterData)
            {
                //Get the number of arguments going in to the parameter
                int count = kvp.Value.Repetitions <= 0 ? arguments.Count() - index
                                                        : kvp.Value.Repetitions;

                if (index >= arguments.Count())
                {
                    //If we've used all our arguments, just add empty ones to satisfy the
                    //method signature for the command
                    Objects.Add(ObjectCreator.CreateDefaultObject(kvp.Key));
                    continue;
                }

                object[] args = arguments.ReadToArray(index, count);

                //If the provided object is already of the required type, add and continue
                if (count == 1 && args[0].GetType() == kvp.Key.ParameterType)
                {
                    Objects.Add(args[0]);
                    continue;
                }

                IObjectConverter converter = Registry.GetConverter(kvp.Key.ParameterType);
                if (converter == null)
                {
                    //Use the object creator to attempt a conversion
                    Objects.Add(ObjectCreator.CreateObject(kvp.Key.ParameterType, args, ctx));
                }
                else
                {
                    //Use a defined converter.
                    object conversion = count > 1 ? converter.ConvertFromArray((string[])args, ctx)
                                                  : converter.ConvertFromString(args[0].ToString(), ctx);

                    if (conversion == null)
                    {
                        throw new CommandParsingException(
                                  ParserFailReason.ParsingFailed,
                                  $"Type conversion failed: Failed to convert '{string.Join(" ", args)}' to Type '{ kvp.Key.ParameterType.Name }'.",
                                  new Exception($"Conversion failed in '{converter.GetType().Name}.{nameof(IObjectConverter.ConvertFromArray)}'")
                                  );
                    }

                    Objects.Add(conversion);
                }

                index += count;
            }
        }