laravel-prometheus-exporter/src/PrometheusServiceProvider.php
2020-09-08 22:22:51 +02:00

114 lines
3.5 KiB
PHP

<?php
namespace Superbalist\LaravelPrometheusExporter;
use Illuminate\Support\Arr;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Arr;
use Prometheus\CollectorRegistry;
use Prometheus\Storage\Adapter;
class PrometheusServiceProvider extends ServiceProvider
{
/**
* Perform post-registration booting of services.
*/
public function boot()
{
$this->publishes([
__DIR__ . '/../config/prometheus.php' => config_path('prometheus.php'),
]);
if (config('prometheus.metrics_route_enabled')) {
$this->loadRoutesFrom(__DIR__ . '/routes.php');
}
$exporter = $this->app->make(PrometheusExporter::class); /* @var PrometheusExporter $exporter */
foreach (config('prometheus.collectors') as $class) {
$collector = $this->app->make($class);
$exporter->registerCollector($collector);
}
}
/**
* Register bindings in the container.
*/
public function register()
{
$this->mergeConfigFrom(__DIR__ . '/../config/prometheus.php', 'prometheus');
$this->app->singleton(PrometheusExporter::class, function ($app) {
$adapter = $app['prometheus.storage_adapter'];
$prometheus = new CollectorRegistry($adapter);
return new PrometheusExporter(config('prometheus.namespace'), $prometheus);
});
$this->app->alias(PrometheusExporter::class, 'prometheus');
$this->app->bind('prometheus.storage_adapter_factory', function () {
return new StorageAdapterFactory();
});
$this->app->bind(Adapter::class, function ($app) {
$factory = $app['prometheus.storage_adapter_factory']; /** @var StorageAdapterFactory $factory */
$driver = config('prometheus.storage_adapter');
$configs = config('prometheus.storage_adapters');
$config = Arr::get($configs, $driver, []);
return $factory->make($driver, $config);
});
$this->app->alias(Adapter::class, 'prometheus.storage_adapter');
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return [
'prometheus',
'prometheus.storage_adapter_factory',
'prometheus.storage_adapter',
];
}
/**
* https://medium.com/@koenhoeijmakers/properly-merging-configs-in-laravel-packages-a4209701746d
* :heart:
*
* Merge the given configuration with the existing configuration.
*
* @param string $path
* @param string $key
* @return void
*/
protected function mergeConfigFrom($path, $key)
{
$config = $this->app['config']->get($key, []);
$this->app['config']->set($key, $this->mergeConfig(require $path, $config));
}
/**
* Merges the configs together and takes multi-dimensional arrays into account.
*
* @param array $original
* @param array $merging
* @return array
*/
protected function mergeConfig(array $original, array $merging)
{
$array = array_merge($original, $merging);
foreach ($original as $key => $value) {
if (! is_array($value)) {
continue;
}
if (! Arr::exists($merging, $key)) {
continue;
}
if (is_numeric($key)) {
continue;
}
$array[$key] = $this->mergeConfig($value, $merging[$key]);
}
return $array;
}
}