87 lines
2.4 KiB
PHP
87 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use App\Models\ImportDatasource;
|
|
use App\Services\ServiceGoogleSheet;
|
|
use App\Services\ServicePbgTask;
|
|
use GuzzleHttp\Client; // Import Guzzle Client
|
|
use Illuminate\Console\Command;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class ScrapingData extends Command
|
|
{
|
|
/**
|
|
* The name and signature of the console command.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $signature = 'app:scraping-data';
|
|
|
|
/**
|
|
* The console command description.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $description = 'Command description';
|
|
|
|
private $client;
|
|
private $service_pbg_task;
|
|
|
|
/**
|
|
* Inject dependencies.
|
|
*/
|
|
public function __construct(Client $client, ServicePbgTask $service_pbg_task)
|
|
{
|
|
parent::__construct();
|
|
$this->client = $client;
|
|
$this->service_pbg_task = $service_pbg_task;
|
|
}
|
|
|
|
/**
|
|
* Execute the console command.
|
|
*/
|
|
public function handle()
|
|
{
|
|
DB::beginTransaction(); // Start transaction
|
|
|
|
try {
|
|
// Create a record with "processing" status
|
|
$import_datasource = ImportDatasource::create([
|
|
'message' => 'Initiating scraping...',
|
|
'response_body' => null,
|
|
'status' => 'processing'
|
|
]);
|
|
|
|
// Run the service
|
|
$service_google_sheet = new ServiceGoogleSheet($import_datasource->id);
|
|
$service_google_sheet->run_service();
|
|
|
|
// Run the ServicePbgTask with injected Guzzle Client
|
|
$this->service_pbg_task->run_service();
|
|
|
|
// Update the record status to "success" after completion
|
|
$import_datasource->update([
|
|
'status' => 'success',
|
|
'message' => 'Scraping completed successfully.'
|
|
]);
|
|
|
|
DB::commit(); // Commit the transaction if everything is successful
|
|
} catch (\Exception $e) {
|
|
DB::rollBack(); // Rollback transaction on error
|
|
|
|
// Log the error for debugging
|
|
Log::error('Scraping failed: ' . $e->getMessage(), ['trace' => $e->getTraceAsString()]);
|
|
|
|
// Handle errors by updating the status to "failed"
|
|
if (isset($import_datasource)) {
|
|
$import_datasource->update([
|
|
'status' => 'failed',
|
|
'response_body' => 'Error: ' . $e->getMessage()
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
}
|