| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="TypeMetadataExtensions.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Diagnostics.CodeAnalysis; |
| | | 9 | | using System.Linq; |
| | | 10 | | |
| | | 11 | | #pragma warning disable IDE0130 |
| | | 12 | | namespace MyNet.Metadata; |
| | | 13 | | #pragma warning restore IDE0130 |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// Query extensions for <see cref="TypeMetadata"/> (runtime consumption, not fluent authoring). |
| | | 17 | | /// </summary> |
| | | 18 | | public static class TypeMetadataExtensions |
| | | 19 | | { |
| | | 20 | | extension(TypeMetadata metadata) |
| | | 21 | | { |
| | | 22 | | /// <summary> |
| | | 23 | | /// Gets the names of properties that have a feature of the specified type. |
| | | 24 | | /// </summary> |
| | | 25 | | public string[] WithFeature<TFeature>(Func<TFeature, bool>? predicate = null) |
| | | 26 | | where TFeature : class |
| | 17028 | 27 | | => [.. metadata.Properties.Where(p => p.Value.TryGetFeature<TFeature>(out var feature) && (predicate is null |
| | 17028 | 28 | | .Select(p => p.Key)]; |
| | | 29 | | |
| | | 30 | | /// <summary> |
| | | 31 | | /// Tries to get a feature for the specified property. |
| | | 32 | | /// </summary> |
| | | 33 | | public bool TryGetFeature<TFeature>(string propertyName, [NotNullWhen(true)] out TFeature? feature) |
| | | 34 | | where TFeature : class |
| | | 35 | | { |
| | 39 | 36 | | feature = null; |
| | | 37 | | |
| | 39 | 38 | | return metadata.Properties.TryGetValue(propertyName, out var property) && property.TryGetFeature(out feature |
| | | 39 | | } |
| | | 40 | | |
| | | 41 | | /// <summary> |
| | | 42 | | /// Gets a feature for the specified property, or <c>null</c> when missing. |
| | | 43 | | /// </summary> |
| | | 44 | | public TFeature? GetFeatureOrDefault<TFeature>(string propertyName) |
| | | 45 | | where TFeature : class |
| | 30 | 46 | | => metadata.TryGetFeature<TFeature>(propertyName, out var feature) ? feature : null; |
| | | 47 | | } |
| | | 48 | | } |
| | | 49 | | |