|
| 1 | +// Copyright (c) .NET Foundation. All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Buffers; |
| 6 | +using System.Collections.Generic; |
| 7 | +using System.Diagnostics.CodeAnalysis; |
| 8 | +using System.Reflection; |
| 9 | +using Microsoft.AspNetCore.Components.Reflection; |
| 10 | +using Microsoft.AspNetCore.Components.Rendering; |
| 11 | +using Microsoft.AspNetCore.Internal; |
| 12 | +using static Microsoft.AspNetCore.Internal.LinkerFlags; |
| 13 | + |
| 14 | +namespace Microsoft.AspNetCore.Components.Routing |
| 15 | +{ |
| 16 | + internal sealed class QueryParameterValueSupplier |
| 17 | + { |
| 18 | + public static void ClearCache() => _cacheByType.Clear(); |
| 19 | + |
| 20 | + private static readonly Dictionary<Type, QueryParameterValueSupplier?> _cacheByType = new(); |
| 21 | + |
| 22 | + // These two arrays contain the same number of entries, and their corresponding positions refer to each other. |
| 23 | + // Holding the info like this means we can use Array.BinarySearch with less custom implementation. |
| 24 | + private readonly ReadOnlyMemory<char>[] _queryParameterNames; |
| 25 | + private readonly QueryParameterDestination[] _destinations; |
| 26 | + |
| 27 | + public static QueryParameterValueSupplier? ForType([DynamicallyAccessedMembers(Component)] Type componentType) |
| 28 | + { |
| 29 | + if (!_cacheByType.TryGetValue(componentType, out var instanceOrNull)) |
| 30 | + { |
| 31 | + // If the component doesn't have any query parameters, store a null value for it |
| 32 | + // so we know the upstream code can't try to render query parameter frames for it. |
| 33 | + var sortedMappings = GetSortedMappings(componentType); |
| 34 | + instanceOrNull = sortedMappings == null ? null : new QueryParameterValueSupplier(sortedMappings); |
| 35 | + _cacheByType.TryAdd(componentType, instanceOrNull); |
| 36 | + } |
| 37 | + |
| 38 | + return instanceOrNull; |
| 39 | + } |
| 40 | + |
| 41 | + private QueryParameterValueSupplier(QueryParameterMapping[] sortedMappings) |
| 42 | + { |
| 43 | + _queryParameterNames = new ReadOnlyMemory<char>[sortedMappings.Length]; |
| 44 | + _destinations = new QueryParameterDestination[sortedMappings.Length]; |
| 45 | + for (var i = 0; i < sortedMappings.Length; i++) |
| 46 | + { |
| 47 | + ref var mapping = ref sortedMappings[i]; |
| 48 | + _queryParameterNames[i] = mapping.QueryParameterName; |
| 49 | + _destinations[i] = mapping.Destination; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + public void RenderParametersFromQueryString(RenderTreeBuilder builder, ReadOnlyMemory<char> queryString) |
| 54 | + { |
| 55 | + // If there's no querystring contents, we can skip renting from the pool |
| 56 | + if (queryString.IsEmpty) |
| 57 | + { |
| 58 | + for (var destinationIndex = 0; destinationIndex < _destinations.Length; destinationIndex++) |
| 59 | + { |
| 60 | + ref var destination = ref _destinations[destinationIndex]; |
| 61 | + var blankValue = destination.IsArray ? destination.Parser.ParseMultiple(default, string.Empty) : null; |
| 62 | + builder.AddAttribute(0, destination.ComponentParameterName, blankValue); |
| 63 | + } |
| 64 | + return; |
| 65 | + } |
| 66 | + |
| 67 | + // Temporary workspace in which we accumulate the data while walking the querystring. |
| 68 | + var valuesByMapping = ArrayPool<StringSegmentAccumulator>.Shared.Rent(_destinations.Length); |
| 69 | + |
| 70 | + try |
| 71 | + { |
| 72 | + // Capture values by destination in a single pass through the querystring |
| 73 | + var queryStringEnumerable = new QueryStringEnumerable(queryString); |
| 74 | + foreach (var suppliedPair in queryStringEnumerable) |
| 75 | + { |
| 76 | + var decodedName = suppliedPair.DecodeName(); |
| 77 | + var mappingIndex = Array.BinarySearch(_queryParameterNames, decodedName, QueryParameterNameComparer.Instance); |
| 78 | + if (mappingIndex >= 0) |
| 79 | + { |
| 80 | + var decodedValue = suppliedPair.DecodeValue(); |
| 81 | + |
| 82 | + if (_destinations[mappingIndex].IsArray) |
| 83 | + { |
| 84 | + valuesByMapping[mappingIndex].Add(decodedValue); |
| 85 | + } |
| 86 | + else |
| 87 | + { |
| 88 | + valuesByMapping[mappingIndex].SetSingle(decodedValue); |
| 89 | + } |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + // Finally, emit the parameter attributes by parsing all the string segments and building arrays |
| 94 | + for (var mappingIndex = 0; mappingIndex < _destinations.Length; mappingIndex++) |
| 95 | + { |
| 96 | + ref var destination = ref _destinations[mappingIndex]; |
| 97 | + ref var values = ref valuesByMapping[mappingIndex]; |
| 98 | + |
| 99 | + var parsedValue = destination.IsArray |
| 100 | + ? destination.Parser.ParseMultiple(values, destination.ComponentParameterName) |
| 101 | + : values.Count == 0 |
| 102 | + ? default |
| 103 | + : destination.Parser.Parse(values[0].Span, destination.ComponentParameterName); |
| 104 | + |
| 105 | + builder.AddAttribute(0, destination.ComponentParameterName, parsedValue); |
| 106 | + } |
| 107 | + } |
| 108 | + finally |
| 109 | + { |
| 110 | + ArrayPool<StringSegmentAccumulator>.Shared.Return(valuesByMapping, true); |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + private static QueryParameterMapping[]? GetSortedMappings([DynamicallyAccessedMembers(Component)] Type componentType) |
| 115 | + { |
| 116 | + var candidateProperties = MemberAssignment.GetPropertiesIncludingInherited(componentType, ComponentProperties.BindablePropertyFlags); |
| 117 | + HashSet<ReadOnlyMemory<char>>? usedQueryParameterNames = null; |
| 118 | + List<QueryParameterMapping>? mappings = null; |
| 119 | + |
| 120 | + foreach (var propertyInfo in candidateProperties) |
| 121 | + { |
| 122 | + if (!propertyInfo.IsDefined(typeof(ParameterAttribute))) |
| 123 | + { |
| 124 | + continue; |
| 125 | + } |
| 126 | + |
| 127 | + var fromQueryAttribute = propertyInfo.GetCustomAttribute<SupplyParameterFromQueryAttribute>(); |
| 128 | + if (fromQueryAttribute is not null) |
| 129 | + { |
| 130 | + // Found a parameter that's assignable from querystring |
| 131 | + var componentParameterName = propertyInfo.Name; |
| 132 | + var queryParameterName = (string.IsNullOrEmpty(fromQueryAttribute.Name) |
| 133 | + ? componentParameterName |
| 134 | + : fromQueryAttribute.Name).AsMemory(); |
| 135 | + |
| 136 | + // If it's an array type, capture that info and prepare to parse the element type |
| 137 | + Type effectiveType = propertyInfo.PropertyType; |
| 138 | + var isArray = false; |
| 139 | + if (effectiveType.IsArray) |
| 140 | + { |
| 141 | + isArray = true; |
| 142 | + effectiveType = effectiveType.GetElementType()!; |
| 143 | + } |
| 144 | + |
| 145 | + if (!UrlValueConstraint.TryGetByTargetType(effectiveType, out var parser)) |
| 146 | + { |
| 147 | + throw new NotSupportedException($"Querystring values cannot be parsed as type '{propertyInfo.PropertyType}'."); |
| 148 | + } |
| 149 | + |
| 150 | + // Add the destination for this component parameter name |
| 151 | + usedQueryParameterNames ??= new(QueryParameterNameComparer.Instance); |
| 152 | + if (usedQueryParameterNames.Contains(queryParameterName)) |
| 153 | + { |
| 154 | + throw new InvalidOperationException($"The component '{componentType}' declares more than one mapping for the query parameter '{queryParameterName}'."); |
| 155 | + } |
| 156 | + usedQueryParameterNames.Add(queryParameterName); |
| 157 | + |
| 158 | + mappings ??= new(); |
| 159 | + mappings.Add(new QueryParameterMapping |
| 160 | + { |
| 161 | + QueryParameterName = queryParameterName, |
| 162 | + Destination = new QueryParameterDestination(componentParameterName, parser, isArray) |
| 163 | + }); |
| 164 | + } |
| 165 | + } |
| 166 | + |
| 167 | + mappings?.Sort((a, b) => QueryParameterNameComparer.Instance.Compare(a.QueryParameterName, b.QueryParameterName)); |
| 168 | + return mappings?.ToArray(); |
| 169 | + } |
| 170 | + |
| 171 | + private readonly struct QueryParameterMapping |
| 172 | + { |
| 173 | + public ReadOnlyMemory<char> QueryParameterName { get; init; } |
| 174 | + public QueryParameterDestination Destination { get; init; } |
| 175 | + } |
| 176 | + |
| 177 | + private readonly struct QueryParameterDestination |
| 178 | + { |
| 179 | + public readonly string ComponentParameterName; |
| 180 | + public readonly UrlValueConstraint Parser; |
| 181 | + public readonly bool IsArray; |
| 182 | + |
| 183 | + public QueryParameterDestination(string componentParameterName, UrlValueConstraint parser, bool isArray) |
| 184 | + { |
| 185 | + ComponentParameterName = componentParameterName; |
| 186 | + Parser = parser; |
| 187 | + IsArray = isArray; |
| 188 | + } |
| 189 | + } |
| 190 | + |
| 191 | + private class QueryParameterNameComparer : IComparer<ReadOnlyMemory<char>>, IEqualityComparer<ReadOnlyMemory<char>> |
| 192 | + { |
| 193 | + public static readonly QueryParameterNameComparer Instance = new(); |
| 194 | + |
| 195 | + public int Compare(ReadOnlyMemory<char> x, ReadOnlyMemory<char> y) |
| 196 | + => x.Span.CompareTo(y.Span, StringComparison.OrdinalIgnoreCase); |
| 197 | + |
| 198 | + public bool Equals(ReadOnlyMemory<char> x, ReadOnlyMemory<char> y) |
| 199 | + => x.Span.Equals(y.Span, StringComparison.OrdinalIgnoreCase); |
| 200 | + |
| 201 | + public int GetHashCode([DisallowNull] ReadOnlyMemory<char> obj) |
| 202 | + => string.GetHashCode(obj.Span, StringComparison.OrdinalIgnoreCase); |
| 203 | + } |
| 204 | + } |
| 205 | +} |
0 commit comments