You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

176 lines
6.2 KiB

  1. /*
  2. * Copyright 2018 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "Private/FIRComponentContainer.h"
  17. #import "Private/FIRAppInternal.h"
  18. #import "Private/FIRComponent.h"
  19. #import "Private/FIRLibrary.h"
  20. #import "Private/FIRLogger.h"
  21. NS_ASSUME_NONNULL_BEGIN
  22. @interface FIRComponentContainer ()
  23. /// The dictionary of components that are registered for a particular app. The key is an NSString
  24. /// of the protocol.
  25. @property(nonatomic, strong) NSMutableDictionary<NSString *, FIRComponentCreationBlock> *components;
  26. /// Cached instances of components that requested to be cached.
  27. @property(nonatomic, strong) NSMutableDictionary<NSString *, id> *cachedInstances;
  28. @end
  29. @implementation FIRComponentContainer
  30. // Collection of all classes that register to provide components.
  31. static NSMutableSet<Class> *sFIRComponentRegistrants;
  32. #pragma mark - Public Registration
  33. + (void)registerAsComponentRegistrant:(Class<FIRLibrary>)klass {
  34. static dispatch_once_t onceToken;
  35. dispatch_once(&onceToken, ^{
  36. sFIRComponentRegistrants = [[NSMutableSet<Class> alloc] init];
  37. });
  38. [self registerAsComponentRegistrant:klass inSet:sFIRComponentRegistrants];
  39. }
  40. + (void)registerAsComponentRegistrant:(Class<FIRLibrary>)klass
  41. inSet:(NSMutableSet<Class> *)allRegistrants {
  42. [allRegistrants addObject:klass];
  43. }
  44. #pragma mark - Internal Initialization
  45. - (instancetype)initWithApp:(FIRApp *)app {
  46. return [self initWithApp:app registrants:sFIRComponentRegistrants];
  47. }
  48. - (instancetype)initWithApp:(FIRApp *)app registrants:(NSMutableSet<Class> *)allRegistrants {
  49. self = [super init];
  50. if (self) {
  51. _app = app;
  52. _cachedInstances = [NSMutableDictionary<NSString *, id> dictionary];
  53. _components = [NSMutableDictionary<NSString *, FIRComponentCreationBlock> dictionary];
  54. [self populateComponentsFromRegisteredClasses:allRegistrants forApp:app];
  55. }
  56. return self;
  57. }
  58. - (void)populateComponentsFromRegisteredClasses:(NSSet<Class> *)classes forApp:(FIRApp *)app {
  59. // Loop through the verified component registrants and populate the components array.
  60. for (Class<FIRLibrary> klass in classes) {
  61. // Loop through all the components being registered and store them as appropriate.
  62. // Classes which do not provide functionality should use a dummy FIRComponentRegistrant
  63. // protocol.
  64. for (FIRComponent *component in [klass componentsToRegister]) {
  65. // Check if the component has been registered before, and error out if so.
  66. NSString *protocolName = NSStringFromProtocol(component.protocol);
  67. if (self.components[protocolName]) {
  68. FIRLogError(kFIRLoggerCore, @"I-COR000029",
  69. @"Attempted to register protocol %@, but it already has an implementation.",
  70. protocolName);
  71. continue;
  72. }
  73. // Store the creation block for later usage.
  74. self.components[protocolName] = component.creationBlock;
  75. // Instantiate the
  76. BOOL shouldInstantiateEager =
  77. (component.instantiationTiming == FIRInstantiationTimingAlwaysEager);
  78. BOOL shouldInstantiateDefaultEager =
  79. (component.instantiationTiming == FIRInstantiationTimingEagerInDefaultApp &&
  80. [app isDefaultApp]);
  81. if (shouldInstantiateEager || shouldInstantiateDefaultEager) {
  82. [self instantiateInstanceForProtocol:component.protocol withBlock:component.creationBlock];
  83. }
  84. }
  85. }
  86. }
  87. #pragma mark - Instance Creation
  88. /// Instantiate an instance of a class that conforms to the specified protocol.
  89. /// This will:
  90. /// - Call the block to create an instance if possible,
  91. /// - Validate that the instance returned conforms to the protocol it claims to,
  92. /// - Cache the instance if the block requests it
  93. - (nullable id)instantiateInstanceForProtocol:(Protocol *)protocol
  94. withBlock:(FIRComponentCreationBlock)creationBlock {
  95. if (!creationBlock) {
  96. return nil;
  97. }
  98. // Create an instance using the creation block.
  99. BOOL shouldCache = NO;
  100. id instance = creationBlock(self, &shouldCache);
  101. if (!instance) {
  102. return nil;
  103. }
  104. // An instance was created, validate that it conforms to the protocol it claims to.
  105. NSString *protocolName = NSStringFromProtocol(protocol);
  106. if (![instance conformsToProtocol:protocol]) {
  107. FIRLogError(kFIRLoggerCore, @"I-COR000030",
  108. @"An instance conforming to %@ was requested, but the instance provided does not "
  109. @"conform to the protocol",
  110. protocolName);
  111. }
  112. // The instance is ready to be returned, but check if it should be cached first before returning.
  113. if (shouldCache) {
  114. self.cachedInstances[protocolName] = instance;
  115. }
  116. return instance;
  117. }
  118. #pragma mark - Internal Retrieval
  119. - (nullable id)instanceForProtocol:(Protocol *)protocol {
  120. // Check if there is a cached instance, and return it if so.
  121. NSString *protocolName = NSStringFromProtocol(protocol);
  122. id cachedInstance = self.cachedInstances[protocolName];
  123. if (cachedInstance) {
  124. return cachedInstance;
  125. }
  126. // Use the creation block to instantiate an instance and return it.
  127. FIRComponentCreationBlock creationBlock = self.components[protocolName];
  128. return [self instantiateInstanceForProtocol:protocol withBlock:creationBlock];
  129. }
  130. #pragma mark - Lifecycle
  131. - (void)removeAllCachedInstances {
  132. // Loop through the cache and notify each instance that is a maintainer to clean up after itself.
  133. for (id instance in self.cachedInstances.allValues) {
  134. if ([instance conformsToProtocol:@protocol(FIRComponentLifecycleMaintainer)] &&
  135. [instance respondsToSelector:@selector(appWillBeDeleted:)]) {
  136. [instance appWillBeDeleted:self.app];
  137. }
  138. }
  139. [self.cachedInstances removeAllObjects];
  140. }
  141. @end
  142. NS_ASSUME_NONNULL_END