Container.php 21.9 KB
Newer Older
1 2
<?php
namespace Civi\Core;
totten's avatar
totten committed
3

4
use Civi\Core\Event\SystemInstallEvent;
5
use Civi\Core\Lock\LockManager;
6
use Symfony\Component\Config\ConfigCache;
7 8
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
9
use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
10
use Symfony\Component\DependencyInjection\Reference;
11
use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass;
12 13 14

// TODO use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;

15 16 17 18
/**
 * Class Container
 * @package Civi\Core
 */
19 20 21 22 23
class Container {

  const SELF = 'civi_container_factory';

  /**
24 25
   * @param bool $reset
   *   Whether to forcibly rebuild the entire container.
26 27
   * @return \Symfony\Component\DependencyInjection\TaggedContainerInterface
   */
28
  public static function singleton($reset = FALSE) {
29 30
    if ($reset || !isset(\Civi::$statics[__CLASS__]['container'])) {
      self::boot(TRUE);
31
    }
32
    return \Civi::$statics[__CLASS__]['container'];
33 34 35
  }

  /**
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
   * Find a cached container definition or construct a new one.
   *
   * There are many weird contexts in which Civi initializes (eg different
   * variations of multitenancy and different permutations of CMS/CRM bootstrap),
   * and hook_container may fire a bit differently in each context. To mitigate
   * risk of leaks between environments, we compute a unique envID
   * (md5(DB_NAME, HTTP_HOST, SCRIPT_FILENAME, etc)) and use separate caches for
   * each (eg "templates_c/CachedCiviContainer.$ENVID.php").
   *
   * Constants:
   *   - CIVICRM_CONTAINER_CACHE -- 'always' [default], 'never', 'auto'
   *   - CIVICRM_DSN
   *   - CIVICRM_DOMAIN_ID
   *   - CIVICRM_TEMPLATE_COMPILEDIR
   *
51
   * @return \Symfony\Component\DependencyInjection\ContainerInterface
52 53 54 55 56 57
   */
  public function loadContainer() {
    // Note: The container's raison d'etre is to manage construction of other
    // services. Consequently, we assume a minimal service available -- the classloader
    // has been setup, and civicrm.settings.php is loaded, but nothing else works.

58
    $cacheMode = defined('CIVICRM_CONTAINER_CACHE') ? CIVICRM_CONTAINER_CACHE : 'auto';
59 60 61

    // In pre-installation environments, don't bother with caching.
    if (!defined('CIVICRM_TEMPLATE_COMPILEDIR') || !defined('CIVICRM_DSN') || $cacheMode === 'never' || \CRM_Utils_System::isInUpgradeMode()) {
62 63 64
      $containerBuilder = $this->createContainer();
      $containerBuilder->compile();
      return $containerBuilder;
65 66
    }

67
    $envId = \CRM_Core_Config_Runtime::getId();
68 69 70 71 72 73 74
    $file = CIVICRM_TEMPLATE_COMPILEDIR . "/CachedCiviContainer.{$envId}.php";
    $containerConfigCache = new ConfigCache($file, $cacheMode === 'auto');
    if (!$containerConfigCache->isFresh()) {
      $containerBuilder = $this->createContainer();
      $containerBuilder->compile();
      $dumper = new PhpDumper($containerBuilder);
      $containerConfigCache->write(
75
        $dumper->dump(['class' => 'CachedCiviContainer']),
76 77 78 79 80 81 82 83 84 85 86 87
        $containerBuilder->getResources()
      );
    }

    require_once $file;
    $c = new \CachedCiviContainer();
    return $c;
  }

  /**
   * Construct a new container.
   *
88
   * @var \Symfony\Component\DependencyInjection\ContainerBuilder
89
   * @return \Symfony\Component\DependencyInjection\ContainerBuilder
90 91 92 93
   */
  public function createContainer() {
    $civicrm_base_path = dirname(dirname(__DIR__));
    $container = new ContainerBuilder();
94 95
    $container->addCompilerPass(new RegisterListenersPass('dispatcher'));
    $container->addObjectResource($this);
96
    $container->setParameter('civicrm_base_path', $civicrm_base_path);
97
    //$container->set(self::SELF, $this);
98 99 100

    $container->addResource(new \Symfony\Component\Config\Resource\FileResource(__FILE__));

101 102
    $container->setDefinition(self::SELF, new Definition(
      'Civi\Core\Container',
103
      []
104
    ));
105

106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
    // TODO Move configuration to an external file; define caching structure
    //    if (empty($configDirectories)) {
    //      throw new \Exception(__CLASS__ . ': Missing required properties (civicrmRoot, configDirectories)');
    //    }
    //    $locator = new FileLocator($configDirectories);
    //    $loaderResolver = new LoaderResolver(array(
    //      new YamlFileLoader($container, $locator)
    //    ));
    //    $delegatingLoader = new DelegatingLoader($loaderResolver);
    //    foreach (array('services.yml') as $file) {
    //      $yamlUserFiles = $locator->locate($file, NULL, FALSE);
    //      foreach ($yamlUserFiles as $file) {
    //        $delegatingLoader->load($file);
    //      }
    //    }
121

122
    $container->setDefinition('angular', new Definition(
123
      'Civi\Angular\Manager',
124
      []
125
    ))
126
      ->setFactory([new Reference(self::SELF), 'createAngularManager']);
127

128
    $container->setDefinition('dispatcher', new Definition(
129
      'Civi\Core\CiviEventDispatcher',
130
      [new Reference('service_container')]
131
    ))
132
      ->setFactory([new Reference(self::SELF), 'createEventDispatcher']);
133

134
    $container->setDefinition('magic_function_provider', new Definition(
135
      'Civi\API\Provider\MagicFunctionProvider',
136
      []
137 138
    ));

139
    $container->setDefinition('civi_api_kernel', new Definition(
140
      'Civi\API\Kernel',
141
      [new Reference('dispatcher'), new Reference('magic_function_provider')]
142
    ))
143
      ->setFactory([new Reference(self::SELF), 'createApiKernel']);
144

145
    $container->setDefinition('cxn_reg_client', new Definition(
146
      'Civi\Cxn\Rpc\RegistrationClient',
147
      []
148
    ))
149
      ->setFactory('CRM_Cxn_BAO_Cxn::createRegistrationClient');
150

151
    $container->setDefinition('psr_log', new Definition('CRM_Core_Error_Log', []));
152

153
    $basicCaches = [
154 155
      'js_strings' => 'js_strings',
      'community_messages' => 'community_messages',
156
      'checks' => 'checks',
157
      'session' => 'CiviCRM Session',
158
      'long' => 'long',
159
      'groups' => 'contact groups',
160
      'navigation' => 'navigation',
161
    ];
162
    foreach ($basicCaches as $cacheSvc => $cacheGrp) {
163 164 165 166 167 168 169 170 171 172 173
      $definitionParams = [
        'name' => $cacheGrp,
        'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
      ];
      // For Caches that we don't really care about the ttl for and/or maybe accessed
      // fairly often we use the fastArrayDecorator which improves reads and writes, these
      // caches should also not have concurrency risk.
      $fastArrayCaches = ['groups'];
      if (in_array($cacheSvc, $fastArrayCaches)) {
        $definitionParams['withArray'] = 'fast';
      }
174
      $container->setDefinition("cache.{$cacheSvc}", new Definition(
175
        'CRM_Utils_Cache_Interface',
176
        [$definitionParams]
177
      ))->setFactory('CRM_Utils_Cache::create');
178
    }
179

180 181 182 183 184 185 186 187 188 189 190 191
    // PrevNextCache cannot use memory or array cache at the moment because the
    // Code in CRM_Core_BAO_PrevNextCache assumes that this cache is sql backed.
    $container->setDefinition("cache.prevNextCache", new Definition(
      'CRM_Utils_Cache_Interface',
      [
        [
          'name' => 'CiviCRM Search PrevNextCache',
          'type' => ['SqlGroup'],
        ],
      ]
    ))->setFactory('CRM_Utils_Cache::create');

192 193
    $container->setDefinition('sql_triggers', new Definition(
      'Civi\Core\SqlTriggers',
194
      []
195 196
    ));

197 198
    $container->setDefinition('asset_builder', new Definition(
      'Civi\Core\AssetBuilder',
199
      []
200 201
    ));

202 203 204 205 206
    $container->setDefinition('themes', new Definition(
      'Civi\Core\Themes',
      []
    ));

207
    $container->setDefinition('pear_mail', new Definition('Mail'))
208
      ->setFactory('CRM_Utils_Mail::createMailer');
209

210 211 212 213
    if (empty(\Civi::$statics[__CLASS__]['boot'])) {
      throw new \RuntimeException("Cannot initialize container. Boot services are undefined.");
    }
    foreach (\Civi::$statics[__CLASS__]['boot'] as $bootService => $def) {
214
      $container->setDefinition($bootService, new Definition())->setSynthetic(TRUE);
215 216
    }

217
    // Expose legacy singletons as services in the container.
218
    $singletons = [
219
      'httpClient' => 'CRM_Utils_HttpClient',
220
      'cache.default' => 'CRM_Utils_Cache',
221
      'i18n' => 'CRM_Core_I18n',
222 223
      // Maybe? 'config' => 'CRM_Core_Config',
      // Maybe? 'smarty' => 'CRM_Core_Smarty',
224
    ];
225 226 227 228
    foreach ($singletons as $name => $class) {
      $container->setDefinition($name, new Definition(
        $class
      ))
229
        ->setFactory([$class, 'singleton']);
230
    }
231
    $container->setAlias('cache.short', 'cache.default');
232

233 234 235
    $container->setDefinition('resources', new Definition(
      'CRM_Core_Resources',
      [new Reference('service_container')]
236
    ))->setFactory([new Reference(self::SELF), 'createResources']);
237

238
    $container->setDefinition('prevnext', new Definition(
239 240
      'CRM_Core_PrevNextCache_Interface',
      [new Reference('service_container')]
241
    ))->setFactory([new Reference(self::SELF), 'createPrevNextCache']);
242 243

    $container->setDefinition('prevnext.driver.sql', new Definition(
244 245 246 247
      'CRM_Core_PrevNextCache_Sql',
      []
    ));

248 249 250 251 252 253
    $container->setDefinition('prevnext.driver.redis', new Definition(
      'CRM_Core_PrevNextCache_Redis',
      [new Reference('cache_config')]
    ));

    $container->setDefinition('cache_config', new Definition('ArrayObject'))
254
      ->setFactory([new Reference(self::SELF), 'createCacheConfig']);
255

256 257
    $container->setDefinition('civi.mailing.triggers', new Definition(
      'Civi\Core\SqlTrigger\TimestampTriggers',
258 259
      ['civicrm_mailing', 'Mailing']
    ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo']);
260

261 262
    $container->setDefinition('civi.activity.triggers', new Definition(
      'Civi\Core\SqlTrigger\TimestampTriggers',
263 264
      ['civicrm_activity', 'Activity']
    ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo']);
265 266 267

    $container->setDefinition('civi.case.triggers', new Definition(
      'Civi\Core\SqlTrigger\TimestampTriggers',
268 269
      ['civicrm_case', 'Case']
    ))->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo']);
270

271 272
    $container->setDefinition('civi.case.staticTriggers', new Definition(
      'Civi\Core\SqlTrigger\StaticTriggers',
273 274 275 276
      [
        [
          [
            'upgrade_check' => ['table' => 'civicrm_case', 'column' => 'modified_date'],
277 278
            'table' => 'civicrm_case_activity',
            'when' => 'AFTER',
279
            'event' => ['INSERT'],
280
            'sql' => "\nUPDATE civicrm_case SET modified_date = CURRENT_TIMESTAMP WHERE id = NEW.case_id;\n",
281 282 283
          ],
          [
            'upgrade_check' => ['table' => 'civicrm_case', 'column' => 'modified_date'],
284 285
            'table' => 'civicrm_activity',
            'when' => 'BEFORE',
286
            'event' => ['UPDATE', 'DELETE'],
287
            'sql' => "\nUPDATE civicrm_case SET modified_date = CURRENT_TIMESTAMP WHERE id IN (SELECT ca.case_id FROM civicrm_case_activity ca WHERE ca.activity_id = OLD.id);\n",
288 289 290
          ],
        ],
      ]
291
    ))
292
      ->addTag('kernel.event_listener', ['event' => 'hook_civicrm_triggerInfo', 'method' => 'onTriggerInfo']);
293

294 295
    $container->setDefinition('civi_token_compat', new Definition(
      'Civi\Token\TokenCompatSubscriber',
296
      []
297
    ))->addTag('kernel.event_subscriber');
298 299
    $container->setDefinition("crm_mailing_action_tokens", new Definition(
      "CRM_Mailing_ActionTokens",
300
      []
301
    ))->addTag('kernel.event_subscriber');
302

303
    foreach (['Activity', 'Contribute', 'Event', 'Mailing', 'Member'] as $comp) {
304 305
      $container->setDefinition("crm_" . strtolower($comp) . "_tokens", new Definition(
        "CRM_{$comp}_Tokens",
306
        []
307 308
      ))->addTag('kernel.event_subscriber');
    }
309

310
    if (\CRM_Utils_Constant::value('CIVICRM_FLEXMAILER_HACK_SERVICES')) {
311
      \Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_SERVICES, [$container]);
312 313
    }

314 315
    \CRM_Utils_Hook::container($container);

316 317 318
    return $container;
  }

319 320 321 322 323 324 325
  /**
   * @return \Civi\Angular\Manager
   */
  public function createAngularManager() {
    return new \Civi\Angular\Manager(\CRM_Core_Resources::singleton());
  }

326
  /**
327
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
328
   * @return \Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher
329
   */
330
  public function createEventDispatcher($container) {
331
    $dispatcher = new CiviEventDispatcher($container);
332 333 334 335 336 337 338 339 340 341
    $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, ['\Civi\Core\InstallationCanary', 'check']);
    $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, ['\Civi\Core\DatabaseInitializer', 'initialize']);
    $dispatcher->addListener(SystemInstallEvent::EVENT_NAME, ['\Civi\Core\LocalizationInitializer', 'initialize']);
    $dispatcher->addListener('hook_civicrm_pre', ['\Civi\Core\Event\PreEvent', 'dispatchSubevent'], 100);
    $dispatcher->addListener('hook_civicrm_post', ['\Civi\Core\Event\PostEvent', 'dispatchSubevent'], 100);
    $dispatcher->addListener('hook_civicrm_post::Activity', ['\Civi\CCase\Events', 'fireCaseChange']);
    $dispatcher->addListener('hook_civicrm_post::Case', ['\Civi\CCase\Events', 'fireCaseChange']);
    $dispatcher->addListener('hook_civicrm_caseChange', ['\Civi\CCase\Events', 'delegateToXmlListeners']);
    $dispatcher->addListener('hook_civicrm_caseChange', ['\Civi\CCase\SequenceListener', 'onCaseChange_static']);
    $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\Core\CiviEventInspector', 'findBuiltInEvents']);
342
    // TODO We need a better code-convention for metadata about non-hook events.
343 344 345 346 347
    $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\API\Events', 'hookEventDefs']);
    $dispatcher->addListener('hook_civicrm_eventDefs', ['\Civi\Core\Event\SystemInstallEvent', 'hookEventDefs']);
    $dispatcher->addListener('hook_civicrm_buildAsset', ['\Civi\Angular\Page\Modules', 'buildAngularModules']);
    $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Utils_VisualBundle', 'buildAssetJs']);
    $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Utils_VisualBundle', 'buildAssetCss']);
348
    $dispatcher->addListener('hook_civicrm_buildAsset', ['\CRM_Core_Resources', 'renderMenubarStylesheet']);
colemanw's avatar
colemanw committed
349
    $dispatcher->addListener('hook_civicrm_coreResourceList', ['\CRM_Utils_System', 'appendCoreResources']);
350
    $dispatcher->addListener('hook_civicrm_getAssetUrl', ['\CRM_Utils_System', 'alterAssetUrl']);
351 352 353 354
    $dispatcher->addListener('civi.dao.postInsert', ['\CRM_Core_BAO_RecurringEntity', 'triggerInsert']);
    $dispatcher->addListener('civi.dao.postUpdate', ['\CRM_Core_BAO_RecurringEntity', 'triggerUpdate']);
    $dispatcher->addListener('civi.dao.postDelete', ['\CRM_Core_BAO_RecurringEntity', 'triggerDelete']);
    $dispatcher->addListener('hook_civicrm_unhandled_exception', [
355 356
      'CRM_Core_LegacyErrorHandler',
      'handleException',
357 358 359 360 361 362 363
    ], -200);
    $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, ['CRM_Activity_ActionMapping', 'onRegisterActionMappings']);
    $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, ['CRM_Contact_ActionMapping', 'onRegisterActionMappings']);
    $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, ['CRM_Contribute_ActionMapping_ByPage', 'onRegisterActionMappings']);
    $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, ['CRM_Contribute_ActionMapping_ByType', 'onRegisterActionMappings']);
    $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, ['CRM_Event_ActionMapping', 'onRegisterActionMappings']);
    $dispatcher->addListener(\Civi\ActionSchedule\Events::MAPPINGS, ['CRM_Member_ActionMapping', 'onRegisterActionMappings']);
364

365
    if (\CRM_Utils_Constant::value('CIVICRM_FLEXMAILER_HACK_LISTENERS')) {
366
      \Civi\Core\Resolver::singleton()->call(CIVICRM_FLEXMAILER_HACK_LISTENERS, [$dispatcher]);
367 368
    }

369 370
    return $dispatcher;
  }
371

372
  /**
373
   * @return \Civi\Core\Lock\LockManager
374
   */
375
  public static function createLockManager() {
376 377 378 379
    // Ideally, downstream implementers could override any definitions in
    // the container. For now, we'll make-do with some define()s.
    $lm = new LockManager();
    $lm
380 381 382 383
      ->register('/^cache\./', defined('CIVICRM_CACHE_LOCK') ? CIVICRM_CACHE_LOCK : ['CRM_Core_Lock', 'createScopedLock'])
      ->register('/^data\./', defined('CIVICRM_DATA_LOCK') ? CIVICRM_DATA_LOCK : ['CRM_Core_Lock', 'createScopedLock'])
      ->register('/^worker\.mailing\.send\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : ['CRM_Core_Lock', 'createCivimailLock'])
      ->register('/^worker\./', defined('CIVICRM_WORK_LOCK') ? CIVICRM_WORK_LOCK : ['CRM_Core_Lock', 'createScopedLock']);
384 385 386 387 388 389 390

    // Registrations may use complex resolver expressions, but (as a micro-optimization)
    // the default factory is specified as an array.

    return $lm;
  }

391 392
  /**
   * @param \Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
Eileen McNaughton's avatar
Eileen McNaughton committed
393 394
   * @param $magicFunctionProvider
   *
395 396
   * @return \Civi\API\Kernel
   */
397
  public function createApiKernel($dispatcher, $magicFunctionProvider) {
398
    $dispatcher->addSubscriber(new \Civi\API\Subscriber\ChainSubscriber());
399
    $dispatcher->addSubscriber(new \Civi\API\Subscriber\TransactionSubscriber());
400
    $dispatcher->addSubscriber(new \Civi\API\Subscriber\I18nSubscriber());
401
    $dispatcher->addSubscriber($magicFunctionProvider);
402
    $dispatcher->addSubscriber(new \Civi\API\Subscriber\PermissionCheck());
403
    $dispatcher->addSubscriber(new \Civi\API\Subscriber\APIv3SchemaAdapter());
404
    $dispatcher->addSubscriber(new \Civi\API\Subscriber\WrapperAdapter([
405 406 407 408
      \CRM_Utils_API_HTMLInputCoder::singleton(),
      \CRM_Utils_API_NullOutputCoder::singleton(),
      \CRM_Utils_API_ReloadOption::singleton(),
      \CRM_Utils_API_MatchOption::singleton(),
409
    ]));
410
    $dispatcher->addSubscriber(new \Civi\API\Subscriber\XDebugSubscriber());
411 412 413 414 415
    $kernel = new \Civi\API\Kernel($dispatcher);

    $reflectionProvider = new \Civi\API\Provider\ReflectionProvider($kernel);
    $dispatcher->addSubscriber($reflectionProvider);

416 417 418
    $dispatcher->addSubscriber(new \Civi\API\Subscriber\DynamicFKAuthorization(
      $kernel,
      'Attachment',
419
      ['create', 'get', 'delete'],
totten's avatar
totten committed
420
      // Given a file ID, determine the entity+table it's attached to.
421 422 423 424
      'SELECT if(cf.id,1,0) as is_valid, cef.entity_table, cef.entity_id
         FROM civicrm_file cf
         LEFT JOIN civicrm_entity_file cef ON cf.id = cef.file_id
         WHERE cf.id = %1',
425 426 427 428 429 430 431 432
      // Get a list of custom fields (field_name,table_name,extends)
      'SELECT concat("custom_",fld.id) as field_name,
        grp.table_name as table_name,
        grp.extends as extends
       FROM civicrm_custom_field fld
       INNER JOIN civicrm_custom_group grp ON fld.custom_group_id = grp.id
       WHERE fld.data_type = "File"
      ',
433
      ['civicrm_activity', 'civicrm_mailing', 'civicrm_contact', 'civicrm_grant']
434 435
    ));

436
    $kernel->setApiProviders([
437 438
      $reflectionProvider,
      $magicFunctionProvider,
439
    ]);
440

441 442
    return $kernel;
  }
443

444
  /**
445
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
446 447 448 449 450 451 452 453 454 455 456
   * @return \CRM_Core_Resources
   */
  public static function createResources($container) {
    $sys = \CRM_Extension_System::singleton();
    return new \CRM_Core_Resources(
      $sys->getMapper(),
      $container->get('cache.js_strings'),
      \CRM_Core_Config::isUpgradeMode() ? NULL : 'resCacheCode'
    );
  }

457
  /**
458
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
459 460 461
   * @return \CRM_Core_PrevNextCache_Interface
   */
  public static function createPrevNextCache($container) {
462 463
    $setting = \Civi::settings()->get('prevNextBackend');
    if ($setting === 'default') {
464 465
      // For initial release (5.8.x), continue defaulting to SQL.
      $isTransitional = version_compare(\CRM_Utils_System::version(), '5.9.alpha1', '<');
466 467
      $cacheDriver = \CRM_Utils_Cache::getCacheDriver();
      $service = 'prevnext.driver.' . strtolower($cacheDriver);
468
      return $container->has($service) && !$isTransitional
469 470 471 472 473 474
        ? $container->get($service)
        : $container->get('prevnext.driver.sql');
    }
    else {
      return $container->get('prevnext.driver.' . $setting);
    }
475 476
  }

477 478 479 480 481 482 483
  public static function createCacheConfig() {
    $driver = \CRM_Utils_Cache::getCacheDriver();
    $settings = \CRM_Utils_Cache::getCacheSettings($driver);
    $settings['driver'] = $driver;
    return new \ArrayObject($settings);
  }

484 485 486 487 488
  /**
   * Get a list of boot services.
   *
   * These are services which must be setup *before* the container can operate.
   *
489
   * @param bool $loadFromDB
490 491
   * @throws \CRM_Core_Exception
   */
492
  public static function boot($loadFromDB) {
493
    // Array(string $serviceId => object $serviceInstance).
494
    $bootServices = [];
495
    \Civi::$statics[__CLASS__]['boot'] = &$bootServices;
496

497
    $bootServices['runtime'] = $runtime = new \CRM_Core_Config_Runtime();
498
    $runtime->initialize($loadFromDB);
499

500
    $bootServices['paths'] = new \Civi\Core\Paths();
501

502
    $class = $runtime->userFrameworkClass;
503
    $bootServices['userSystem'] = $userSystem = new $class();
504 505 506
    $userSystem->initialize();

    $userPermissionClass = 'CRM_Core_Permission_' . $runtime->userFramework;
507
    $bootServices['userPermissionClass'] = new $userPermissionClass();
508

509
    $bootServices['cache.settings'] = \CRM_Utils_Cache::create([
510
      'name' => 'settings',
511 512
      'type' => ['*memory*', 'SqlGroup', 'ArrayCache'],
    ]);
513

514
    $bootServices['settings_manager'] = new \Civi\Core\SettingsManager($bootServices['cache.settings']);
515

516
    $bootServices['lockManager'] = self::createLockManager();
517 518

    if ($loadFromDB && $runtime->dsn) {
519
      \CRM_Core_DAO::init($runtime->dsn);
520
      \CRM_Utils_Hook::singleton(TRUE);
521
      \CRM_Extension_System::singleton(TRUE);
522
      \CRM_Extension_System::singleton(TRUE)->getClassLoader()->register();
523

deb.monish's avatar
deb.monish committed
524 525
      $runtime->includeCustomPath();

526
      $c = new self();
527 528 529 530 531
      $container = $c->loadContainer();
      foreach ($bootServices as $name => $obj) {
        $container->set($name, $obj);
      }
      \Civi::$statics[__CLASS__]['container'] = $container;
532 533 534 535
    }
  }

  public static function getBootService($name) {
536
    return \Civi::$statics[__CLASS__]['boot'][$name];
537 538
  }

539 540 541 542 543 544 545 546 547
  /**
   * Determine whether the container services are available.
   *
   * @return bool
   */
  public static function isContainerBooted() {
    return isset(\Civi::$statics[__CLASS__]['container']);
  }

548
}