pilot-sdk/src/Laravel/PilotServiceProvider.php

98 lines
2.4 KiB
PHP

<?php
namespace Bluesquare\Pilot\Laravel;
use Bluesquare\Pilot\Pilot;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;
class PilotServiceProvider extends ServiceProvider
{
protected $pilot;
/**
* Register services.
*/
public function register(): void
{
$this->mergeConfigFrom(
__DIR__.'/config/pilot.php', 'pilot'
);
}
/**
* Bootstrap services.
*/
public function boot(): void
{
$this->publishes([
__DIR__.'/config/pilot.php' => config_path('pilot.php'),
], 'config');
$this->registerPilot();
Route::any('api/pilot', function (Request $request) {
return $this->handleRequest($request);
});
}
protected function registerPilot()
{
$this->pilot = new Pilot;
try {
$actions = app('files')->allFiles(app_path('Pilot/Actions'));
foreach ($actions as $action) {
$class = 'App\\Pilot\\Actions\\' . $action->getBasename('.php');
if (class_exists($class)) {
$action = new $class;
$this->pilot->action($action->slug(), [$action, 'handle']);
}
}
}
catch (\Exception $e) {}
try {
$metrics = app('files')->allFiles(app_path('Pilot/Metrics'));
foreach ($metrics as $metric) {
$class = 'App\\Pilot\\Metrics\\' . $metric->getBasename('.php');
if (class_exists($class)) {
$metric = new $class;
$this->pilot->metric($metric->slug(), [$metric, 'handle']);
}
}
}
catch (\Exception $e) {}
}
protected function handleRequest(Request $request)
{
if (empty(config('pilot.key')) || config('pilot.key') != $request->bearerToken()) {
abort(403);
}
$output = $this->pilot->handle($request->all(), $request->files->all());
if (isset($output['json'])) {
return response()->json($output['json']);
}
if (isset($output['file'])) {
return response()->download(
$output['file']['content'],
$output['file']['name'],
[
'Content-Type' => $output['file']['type'],
]
);
}
return response();
}
}