You've already forked pilot-sdk
110 lines
3.0 KiB
PHP
110 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace Bluesquare\Pilot\Laravel;
|
|
|
|
use Bluesquare\Pilot\Laravel\Middlewares\CheckPilotToken;
|
|
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);
|
|
});
|
|
|
|
Route::aliasMiddleware('pilot', CheckPilotToken::class);
|
|
|
|
$this->commands([
|
|
\Bluesquare\Pilot\Laravel\Commands\MakeAction::class,
|
|
\Bluesquare\Pilot\Laravel\Commands\MakeMetric::class,
|
|
]);
|
|
}
|
|
|
|
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;
|
|
|
|
if (method_exists($action, 'form'))
|
|
$this->pilot->form($action->slug(), [$action, 'form']);
|
|
|
|
$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->allFiles());
|
|
|
|
if (isset($output['json'])) {
|
|
return response()->json($output['json']);
|
|
}
|
|
|
|
if (isset($output['file'])) {
|
|
return response()->download(
|
|
$output['file']['path'],
|
|
$output['file']['name'] ?? null,
|
|
! empty($output['file']['type']) ? [
|
|
'Content-Type' => $output['file']['type'],
|
|
] : []
|
|
)->deleteFileAfterSend(isset($output['file']['deleteAfterDownload']) ? $output['file']['deleteAfterDownload'] : false);
|
|
}
|
|
|
|
return response();
|
|
}
|
|
}
|