FIRComponentContainer.m 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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 instance if it has requested to be instantiated.
  76. BOOL shouldInstantiateEager =
  77. (component.instantiationTiming == FIRInstantiationTimingAlwaysEager);
  78. BOOL shouldInstantiateDefaultEager =
  79. (component.instantiationTiming == FIRInstantiationTimingEagerInDefaultApp &&
  80. [app isDefaultApp]);
  81. if (shouldInstantiateEager || shouldInstantiateDefaultEager) {
  82. @synchronized(self) {
  83. [self instantiateInstanceForProtocol:component.protocol
  84. withBlock:component.creationBlock];
  85. }
  86. }
  87. }
  88. }
  89. }
  90. #pragma mark - Instance Creation
  91. /// Instantiate an instance of a class that conforms to the specified protocol.
  92. /// This will:
  93. /// - Call the block to create an instance if possible,
  94. /// - Validate that the instance returned conforms to the protocol it claims to,
  95. /// - Cache the instance if the block requests it
  96. ///
  97. /// Note that this method assumes the caller already has @sychronized on self.
  98. - (nullable id)instantiateInstanceForProtocol:(Protocol *)protocol
  99. withBlock:(FIRComponentCreationBlock)creationBlock {
  100. if (!creationBlock) {
  101. return nil;
  102. }
  103. // Create an instance using the creation block.
  104. BOOL shouldCache = NO;
  105. id instance = creationBlock(self, &shouldCache);
  106. if (!instance) {
  107. return nil;
  108. }
  109. // An instance was created, validate that it conforms to the protocol it claims to.
  110. NSString *protocolName = NSStringFromProtocol(protocol);
  111. if (![instance conformsToProtocol:protocol]) {
  112. FIRLogError(kFIRLoggerCore, @"I-COR000030",
  113. @"An instance conforming to %@ was requested, but the instance provided does not "
  114. @"conform to the protocol",
  115. protocolName);
  116. }
  117. // The instance is ready to be returned, but check if it should be cached first before returning.
  118. if (shouldCache) {
  119. self.cachedInstances[protocolName] = instance;
  120. }
  121. return instance;
  122. }
  123. #pragma mark - Internal Retrieval
  124. - (nullable id)instanceForProtocol:(Protocol *)protocol {
  125. // Check if there is a cached instance, and return it if so.
  126. NSString *protocolName = NSStringFromProtocol(protocol);
  127. id cachedInstance;
  128. @synchronized(self) {
  129. cachedInstance = self.cachedInstances[protocolName];
  130. if (!cachedInstance) {
  131. // Use the creation block to instantiate an instance and return it.
  132. FIRComponentCreationBlock creationBlock = self.components[protocolName];
  133. cachedInstance = [self instantiateInstanceForProtocol:protocol withBlock:creationBlock];
  134. }
  135. }
  136. return cachedInstance;
  137. }
  138. #pragma mark - Lifecycle
  139. - (void)removeAllCachedInstances {
  140. @synchronized(self) {
  141. // Loop through the cache and notify each instance that is a maintainer to clean up after
  142. // itself.
  143. for (id instance in self.cachedInstances.allValues) {
  144. if ([instance conformsToProtocol:@protocol(FIRComponentLifecycleMaintainer)] &&
  145. [instance respondsToSelector:@selector(appWillBeDeleted:)]) {
  146. [instance appWillBeDeleted:self.app];
  147. }
  148. }
  149. // Empty the cache.
  150. [self.cachedInstances removeAllObjects];
  151. }
  152. }
  153. @end
  154. NS_ASSUME_NONNULL_END