Skip to content

Commit

Permalink
💫 Update: RNIDictionarySynthesizable
Browse files Browse the repository at this point in the history
Related:
* TODO:2023-03-04-06-34-28 - Library Native Cleanup
  • Loading branch information
dominicstop committed Mar 26, 2023
1 parent 3f12d71 commit 06b2ecc
Showing 1 changed file with 52 additions and 4 deletions.
56 changes: 52 additions & 4 deletions ios/src_library/Helpers+Utilities/RNIDictionarySynthesizable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,72 @@

import Foundation


public protocol RNIDictionarySynthesizable {

/// The names/identifiers of the property to be ignored when
/// `synthesizedDictionary` is created.
///
static var synthesizedDictionaryIgnore: [String] { get };

/// The key path to the property that will be inlined/"squashed together" into
/// `synthesizedDictionary`.
///
static var synthesizedDictionaryInlinedProperties: [PartialKeyPath<Self>] { get };

/// A map of the property names and their respective values
var synthesizedDictionary: Dictionary<String, Any> { get };

};

extension RNIDictionarySynthesizable {

public static var synthesizedDictionaryIgnore: [String] {
[];
};

public static var synthesizedDictionaryInlinedProperties: [PartialKeyPath<Self>] {
[];
};

public var synthesizedDictionary: Dictionary<String, Any> {
let mirror = Mirror(reflecting: self);
let properties = mirror.children;

#if DEBUG
for propertyKeyToIgnore in Self.synthesizedDictionaryIgnore {
if !properties.contains(where: { $0.label == propertyKeyToIgnore }) {
fatalError(
"Invalid value of '\(propertyKeyToIgnore)' in "
+ "'synthesizedDictionaryIgnore' for '\(Self.self)' - "
+ "No property named '\(propertyKeyToIgnore)' in '\(Self.self)'"
);
};
};
#endif

let propertyValueMap = properties.lazy.map { (
property: String?, value: Any) -> (String, Any)? in
propertyKey: String?, value: Any) -> (String, Any)? in

guard let property = property else { return nil }
return (property, value)
guard let propertyKey = propertyKey,
!Self.synthesizedDictionaryIgnore.contains(propertyKey)
else { return nil };

return (propertyKey, value)
};

return Dictionary(
var baseDict = Dictionary(
uniqueKeysWithValues: propertyValueMap.compactMap { $0 }
);

Self.synthesizedDictionaryInlinedProperties.forEach {
guard let value = self[keyPath: $0] as? (any RNIDictionarySynthesizable)
else { return };

baseDict =
baseDict.merging(value.synthesizedDictionary){ old, _ in old };
};

return baseDict;
};
};

0 comments on commit 06b2ecc

Please sign in to comment.