| | 1 | | namespace Songhay.Extensions; |
| | 2 | |
|
| | 3 | | /// <summary> |
| | 4 | | /// Extensions of <see cref="UriTemplate"/> |
| | 5 | | /// </summary> |
| | 6 | | public static class UriTemplateExtensions |
| | 7 | | { |
| | 8 | | /// <summary> |
| | 9 | | /// Binds the <see cref="UriTemplate"/> |
| | 10 | | /// to the specified <c>params</c> by position. |
| | 11 | | /// </summary> |
| | 12 | | /// <param name="template">The template.</param> |
| | 13 | | /// <param name="values">The values.</param> |
| | 14 | | public static Uri? BindByPosition(this UriTemplate? template, params string[] values) => |
| 3 | 15 | | template.BindByPosition(baseUri: null, values: values); |
| | 16 | |
|
| | 17 | | /// <summary> |
| | 18 | | /// Binds the <see cref="UriTemplate" /> |
| | 19 | | /// to the specified <c>params</c> by position. |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="template">The template.</param> |
| | 22 | | /// <param name="baseUri">The base URI.</param> |
| | 23 | | /// <param name="values">The values.</param> |
| | 24 | | public static Uri? BindByPosition(this UriTemplate? template, Uri? baseUri, params string[] values) |
| 3 | 25 | | { |
| 3 | 26 | | ArgumentNullException.ThrowIfNull(template); |
| | 27 | |
|
| 3 | 28 | | var keys = template.GetParameterNames().ToReferenceTypeValueOrThrow().ToArray(); |
| | 29 | |
|
| 16 | 30 | | for (int i = 0; i < keys.Length; i++) |
| 5 | 31 | | { |
| 5 | 32 | | template.AddParameter(keys[i], values.ElementAtOrDefault(i)); |
| 5 | 33 | | } |
| | 34 | |
|
| 3 | 35 | | var resolved = template.Resolve(); |
| 3 | 36 | | if (baseUri != null) |
| 0 | 37 | | { |
| 0 | 38 | | return new UriBuilder(baseUri).WithPath(resolved)!.Uri; |
| | 39 | | } |
| | 40 | |
|
| 3 | 41 | | var isAbsolute = Uri.IsWellFormedUriString(resolved, UriKind.Absolute); |
| 3 | 42 | | var isRelative = Uri.IsWellFormedUriString(resolved, UriKind.Relative); |
| 3 | 43 | | if (!isAbsolute && !isRelative) |
| 0 | 44 | | throw new FormatException($"The resolved URI template, {resolved}, is in an unknown format."); |
| | 45 | |
|
| 3 | 46 | | return isAbsolute ? new Uri(resolved, UriKind.Absolute) : new Uri(resolved, UriKind.Relative); |
| 3 | 47 | | } |
| | 48 | | } |