Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
96.09% covered (success)
96.09%
123 / 128
50.00% covered (danger)
50.00%
2 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
ApieServiceProvider
96.09% covered (success)
96.09%
123 / 128
50.00% covered (danger)
50.00%
2 / 4
26
0.00% covered (danger)
0.00%
0 / 1
 autoTagHashmapActions
94.74% covered (success)
94.74%
18 / 19
0.00% covered (danger)
0.00%
0 / 1
4.00
 boot
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
4
 register
94.37% covered (success)
94.37%
67 / 71
0.00% covered (danger)
0.00%
0 / 1
14.04
 sanitizeConfig
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2namespace Apie\LaravelApie;
3
4use Apie\ApieCommonPlugin\ApieCommonPluginServiceProvider;
5use Apie\CmsApiDropdownOption\CmsDropdownServiceProvider;
6use Apie\Common\CommonServiceProvider;
7use Apie\Common\ContextBuilders\FrameworkContextBuilder;
8use Apie\Common\Interfaces\BoundedContextSelection;
9use Apie\Common\Interfaces\DashboardContentFactoryInterface;
10use Apie\Common\Wrappers\BoundedContextHashmapFactory;
11use Apie\Common\Wrappers\ConsoleCommandFactory as CommonConsoleCommandFactory;
12use Apie\Console\ConsoleServiceProvider;
13use Apie\Core\CoreServiceProvider;
14use Apie\Core\Session\CsrfTokenProvider;
15use Apie\DoctrineEntityConverter\DoctrineEntityConverterProvider;
16use Apie\DoctrineEntityDatalayer\Commands\ApieUpdateIdfCommand;
17use Apie\DoctrineEntityDatalayer\DoctrineEntityDatalayerServiceProvider;
18use Apie\DoctrineEntityDatalayer\EntityReindexer;
19use Apie\DoctrineEntityDatalayer\IndexStrategy\BackgroundIndexStrategy;
20use Apie\DoctrineEntityDatalayer\IndexStrategy\DirectIndexStrategy;
21use Apie\DoctrineEntityDatalayer\IndexStrategy\IndexAfterResponseIsSentStrategy;
22use Apie\DoctrineEntityDatalayer\IndexStrategy\IndexStrategyInterface;
23use Apie\Faker\FakerServiceProvider;
24use Apie\HtmlBuilders\ErrorHandler\CmsErrorRenderer;
25use Apie\HtmlBuilders\HtmlBuilderServiceProvider;
26use Apie\LaravelApie\Config\LaravelConfiguration;
27use Apie\LaravelApie\ContextBuilders\CsrfTokenContextBuilder;
28use Apie\LaravelApie\ContextBuilders\RegisterBoundedContextActionContextBuilder;
29use Apie\LaravelApie\ContextBuilders\SessionContextBuilder;
30use Apie\LaravelApie\ErrorHandler\ApieErrorRenderer;
31use Apie\LaravelApie\ErrorHandler\Handler;
32use Apie\LaravelApie\Providers\CmsServiceProvider;
33use Apie\LaravelApie\Providers\SecurityServiceProvider;
34use Apie\LaravelApie\Wrappers\Cms\DashboardContentFactory;
35use Apie\LaravelApie\Wrappers\Core\BoundedContextSelected;
36use Apie\LaravelApie\Wrappers\Queue\BackgroundProcessPersistListener;
37use Apie\Maker\MakerServiceProvider;
38use Apie\RestApi\RestApiServiceProvider;
39use Apie\SchemaGenerator\SchemaGeneratorServiceProvider;
40use Apie\Serializer\SerializerServiceProvider;
41use Apie\ServiceProviderGenerator\TagMap;
42use Illuminate\Config\Repository;
43use Illuminate\Contracts\Debug\ExceptionHandler;
44use Illuminate\Contracts\Events\Dispatcher;
45use Illuminate\Support\ServiceProvider;
46use Psr\EventDispatcher\EventDispatcherInterface;
47use Psr\Http\Message\ServerRequestInterface;
48use Symfony\Component\Config\ConfigCache;
49use Symfony\Component\Config\Definition\Processor;
50use Symfony\Component\Config\Resource\ReflectionClassResource;
51use Symfony\Component\Console\Application;
52use Symfony\Component\EventDispatcher\EventDispatcher;
53use Symfony\Component\Lock\LockFactory;
54
55class ApieServiceProvider extends ServiceProvider
56{
57    /**
58     * @var array<string, array<int, class-string<ServiceProvider>>> $dependencies
59     */
60    private array $dependencies = [
61        'enable_common_plugin' => [
62            ApieCommonPluginServiceProvider::class,
63        ],
64        'enable_cms' => [
65            CommonServiceProvider::class,
66            HtmlBuilderServiceProvider::class, // it's important that this loads before CmsServiceProvider!!!
67            CmsServiceProvider::class,
68            SerializerServiceProvider::class,
69        ],
70        'enable_cms_dropdown' => [
71            CommonServiceProvider::class,
72            CmsDropdownServiceProvider::class,
73        ],
74        'enable_core' => [
75            CoreServiceProvider::class,
76        ],
77        'enable_console' => [
78            CommonServiceProvider::class,
79            ConsoleServiceProvider::class,
80            SerializerServiceProvider::class,
81        ],
82        'enable_doctrine_entity_converter' => [
83            CoreServiceProvider::class,
84            DoctrineEntityConverterProvider::class,
85        ],
86        'enable_doctrine_entity_datalayer' => [
87            CoreServiceProvider::class,
88            DoctrineEntityConverterProvider::class,
89            DoctrineEntityDatalayerServiceProvider::class,
90        ],
91        'enable_security' => [
92            CommonServiceProvider::class,
93            SerializerServiceProvider::class,
94            SecurityServiceProvider::class,
95        ],
96        'enable_rest_api' => [
97            CommonServiceProvider::class,
98            RestApiServiceProvider::class,
99            SchemaGeneratorServiceProvider::class,
100            SerializerServiceProvider::class,
101        ],
102        'enable_faker' => [
103            FakerServiceProvider::class,
104        ],
105        'enable_maker' => [
106            MakerServiceProvider::class,
107        ],
108    ];
109
110    private function autoTagHashmapActions(): void
111    {
112        $boundedContextConfig = config('apie.bounded_contexts');
113        $scanBoundedContextConfig = config('apie.scan_bounded_contexts');
114        $factory = new BoundedContextHashmapFactory(
115            $boundedContextConfig ?? [],
116            $scanBoundedContextConfig ?? [],
117            new EventDispatcher(),
118        );
119        $hashmap = $factory->create();
120        foreach ($hashmap as $boundedContext) {
121            foreach ($boundedContext->actions as $action) {
122                $class = $action->getDeclaringClass();
123                if (!$class->isInstantiable()) {
124                    continue;
125                }
126                $className = $class->name;
127                TagMap::register(
128                    $this->app,
129                    $className,
130                    ['apie.context']
131                );
132            }
133        }
134    }
135
136    public function boot(): void
137    {
138        $this->autoTagHashmapActions();
139        $this->loadViewsFrom(__DIR__ . '/../templates', 'apie');
140        $this->loadRoutesFrom(__DIR__.'/../resources/routes.php');
141        TagMap::registerEvents($this->app);
142
143        if ($this->app->runningInConsole()) {
144            $commands = [];
145            $commands[] = ApieUpdateIdfCommand::class;
146            // for some reason these are not called in integration tests without re-registering them
147            foreach (TagMap::getServiceIdsWithTag($this->app, 'console.command') as $taggedCommand) {
148                $serviceId = 'apie.console.tagged.' . $taggedCommand;
149                $this->app->singleton($serviceId, function () use ($taggedCommand) {
150                    return $this->app->get($taggedCommand);
151                });
152                $commands[] = $serviceId;
153            }
154            /** @var CommonConsoleCommandFactory $factory */
155            $factory = $this->app->get('apie.console.factory');
156            foreach ($factory->create($this->app->get(Application::class)) as $command) {
157                $serviceId = 'apie.console.registered.' . $command->getName();
158                $this->app->instance($serviceId, $command);
159                $commands[] = $serviceId;
160            }
161            $this->commands($commands);
162        }
163    }
164
165    public function register()
166    {
167        $this->mergeConfigFrom(__DIR__ . '/../resources/apie.php', 'apie');
168
169        $this->app->bind(FrameworkContextBuilder::class, function () {
170            return new FrameworkContextBuilder('laravel');
171        });
172        TagMap::register($this->app, FrameworkContextBuilder::class, ['apie.core.context_builder']);
173
174        // add PSR-14 support if needed:
175        if (!$this->app->bound(EventDispatcherInterface::class)) {
176            $this->app->bind(EventDispatcherInterface::class, function () {
177                return new class($this->app->make(Dispatcher::class)) implements EventDispatcherInterface {
178                    public function __construct(private readonly Dispatcher $dispatcher)
179                    {
180                    }
181
182                    public function dispatch(object $event): object
183                    {
184                        $this->dispatcher->dispatch($event);
185                        return $event;
186                    }
187                };
188            });
189        }
190
191        // fix for https://github.com/laravel/framework/issues/30415
192        $this->app->extend(
193            ServerRequestInterface::class,
194            function (ServerRequestInterface $psrRequest) {
195                $route = $this->app->make('request')->route();
196                if ($route) {
197                    $parameters = $route->parameters();
198                    foreach ($parameters as $key => $value) {
199                        $psrRequest = $psrRequest->withAttribute($key, $value);
200                    }
201                }
202                return $psrRequest;
203            }
204        );
205
206        $this->app->bind(IndexStrategyInterface::class, function () {
207            $config = config();
208            if ($config->get('apie.enable_doctrine_entity_datalayer')) {
209                $type = $config->get('apie.doctrine.indexing.type', 'direct');
210                return match ($type) {
211                    'direct' => new DirectIndexStrategy($this->app->get(EntityReindexer::class)),
212                    'late' => new IndexAfterResponseIsSentStrategy($this->app->get(EntityReindexer::class)),
213                    'background' => new BackgroundIndexStrategy(),
214                    default => $this->app->get(config('apie.doctrine.indexing.service', DirectIndexStrategy::class)),
215                };
216            }
217
218            return new DirectIndexStrategy($this->app->get(EntityReindexer::class));
219        });
220
221        $this->app->bind(ApieErrorRenderer::class, function () {
222            return new ApieErrorRenderer(
223                $this->app->bound(CmsErrorRenderer::class) ? $this->app->make(CmsErrorRenderer::class) : null,
224                $this->app->make(\Apie\Common\ErrorHandler\ApiErrorRenderer::class),
225                config('apie.cms.base_url')
226            );
227        });
228
229        $this->app->extend(ExceptionHandler::class, function (ExceptionHandler $service) {
230            return new Handler($this->app, $service);
231        });
232
233        $this->app->bind(LockFactory::class, function () {
234            $config = config('apie.lock_store');
235            return new LockFactory($this->app->get($config));
236        });
237        
238        $this->app->bind(DashboardContentFactoryInterface::class, DashboardContentFactory::class);
239        $this->app->bind(BoundedContextSelection::class, BoundedContextSelected::class);
240
241        $alreadyRegistered = [];
242        foreach ($this->dependencies as $configKey => $dependencies) {
243            if (config('apie.' . $configKey, false)) {
244                foreach ($dependencies as $dependency) {
245                    if (!isset($alreadyRegistered[$dependency])) {
246                        $alreadyRegistered[$dependency] = $dependency;
247                        $this->app->register($dependency);
248                    }
249                }
250            }
251        }
252        //$this->app->bind(CsrfTokenProvider::class, CsrfTokenContextBuilder::class);
253        TagMap::register($this->app, CsrfTokenContextBuilder::class, ['apie.core.context_builder']);
254        $this->app->tag(CsrfTokenContextBuilder::class, ['apie.core.context_builder']);
255
256        // this has to be added after CsrfTokenContextBuilder!
257        $this->app->bind(SessionContextBuilder::class);
258        TagMap::register($this->app, SessionContextBuilder::class, ['apie.core.context_builder']);
259        $this->app->tag(SessionContextBuilder::class, ['apie.core.context_builder']);
260
261        TagMap::register($this->app, RegisterBoundedContextActionContextBuilder::class, ['apie.core.context_builder']);
262        $this->app->tag(RegisterBoundedContextActionContextBuilder::class, ['apie.core.context_builder']);
263        $this->app->extend('config', function (Repository $config) {
264            $this->sanitizeConfig($config);
265            return $config;
266        });
267
268        TagMap::register($this->app, BackgroundProcessPersistListener::class, ['kernel.event_subscriber']);
269    }
270
271    private function sanitizeConfig(Repository $config): void
272    {
273        $rawConfig = $config->get('apie');
274        $path = storage_path('framework/cache/apie-config' . md5(json_encode($rawConfig)) . '.php');
275        $resources = [
276            new ReflectionClassResource(new \ReflectionClass(LaravelConfiguration::class)),
277            new ReflectionClassResource(new \ReflectionClass(static::class)),
278        ];
279        $configCache = new ConfigCache($path, true);
280        if ($configCache->isFresh()) {
281            $processedConfig = require $path;
282        } else {
283            $configuration = new LaravelConfiguration();
284
285            $processor = new Processor();
286
287            $processedConfig = $processor->processConfiguration($configuration, ['apie' => $rawConfig]);
288
289            if (!isset($processedConfig['scan_bounded_contexts'])) {
290                $processedConfig['scan_bounded_contexts'] = [];
291            }
292            if (empty($processedConfig['storage'])) {
293                $processedConfig['storage'] = null;
294            }
295            $code = '<?php' . PHP_EOL . 'return ' . var_export($processedConfig, true) . ';';
296            $configCache->write($code, $resources);
297        }
298
299        $config->set('apie', $processedConfig);
300    }
301}