api4 - Import CRM/, Civi/, templates/, ang/, css/, js/, xml/menu
[civicrm-core.git] / CRM / Api4 / Services.php
1 <?php
2
3 use Symfony\Component\DependencyInjection\Reference;
4 use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
5 use Symfony\Component\Config\FileLocator;
6
7 class CRM_Api4_Services {
8
9 /**
10 * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
11 */
12 public static function hook_container($container) {
13 $loader = new XmlFileLoader($container, new FileLocator(dirname(dirname(__DIR__))));
14 $loader->load('Civi/Api4/services.xml');
15
16 self::loadServices('Civi\Api4\Service\Spec\Provider', 'spec_provider', $container);
17 self::loadServices('Civi\Api4\Event\Subscriber', 'event_subscriber', $container);
18
19 $container->getDefinition('civi_api_kernel')->addMethodCall(
20 'registerApiProvider',
21 [new Reference('action_object_provider')]
22 );
23
24 // add event subscribers$container->get(
25 $dispatcher = $container->getDefinition('dispatcher');
26 $subscribers = $container->findTaggedServiceIds('event_subscriber');
27
28 foreach (array_keys($subscribers) as $subscriber) {
29 $dispatcher->addMethodCall(
30 'addSubscriber',
31 [new Reference($subscriber)]
32 );
33 }
34
35 // add spec providers
36 $providers = $container->findTaggedServiceIds('spec_provider');
37 $gatherer = $container->getDefinition('spec_gatherer');
38
39 foreach (array_keys($providers) as $provider) {
40 $gatherer->addMethodCall(
41 'addSpecProvider',
42 [new Reference($provider)]
43 );
44 }
45
46 if (defined('CIVICRM_UF') && CIVICRM_UF === 'UnitTests') {
47 $loader->load('tests/phpunit/api/v4/services.xml');
48 }
49 }
50
51 /**
52 * Load all services in a given directory
53 *
54 * @param string $namespace
55 * @param string $tag
56 * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
57 */
58 public static function loadServices($namespace, $tag, $container) {
59 $namespace = \CRM_Utils_File::addTrailingSlash($namespace, '\\');
60 foreach (\CRM_Extension_System::singleton()->getMapper()->getActiveModuleFiles() as $ext) {
61 $path = \CRM_Utils_File::addTrailingSlash(dirname($ext['filePath'])) . str_replace('\\', DIRECTORY_SEPARATOR, $namespace);
62 foreach (glob("$path*.php") as $file) {
63 $matches = [];
64 preg_match('/(\w*).php/', $file, $matches);
65 $serviceName = $namespace . array_pop($matches);
66 $serviceClass = new \ReflectionClass($serviceName);
67 if ($serviceClass->isInstantiable()) {
68 $definition = $container->register(str_replace('\\', '_', $serviceName), $serviceName);
69 $definition->addTag($tag);
70 }
71 }
72 }
73 }
74
75 }