| 1 |
<?php |
| 2 |
|
| 3 |
namespace Cookiez\Modules\Scanner\Rest; |
| 4 |
|
| 5 |
use Cookiez\Classes\Logger; |
| 6 |
use Cookiez\Classes\Rest\Sanitizer; |
| 7 |
use Cookiez\Modules\Scanner\Classes\{ |
| 8 |
Route_Base, |
| 9 |
Service\Exceptions\Scan_Service_Client_Exception, |
| 10 |
Service\Exceptions\Scan_Transport_Exception, |
| 11 |
}; |
| 12 |
use Cookiez\Modules\Scanner\Components\Scanner; |
| 13 |
use Cookiez\Modules\Scanner\Database\Scan_Entry; |
| 14 |
use Throwable; |
| 15 |
use WP_REST_Response; |
| 16 |
|
| 17 |
if ( ! defined( 'ABSPATH' ) ) { |
| 18 |
exit; |
| 19 |
} |
| 20 |
|
| 21 |
/** |
| 22 |
* Class Get_Scan |
| 23 |
* REST endpoint for retrieving a scan by ID, refreshing from the external |
| 24 |
* service if the local status is still in-progress. |
| 25 |
*/ |
| 26 |
class Get_Scan extends Route_Base { |
| 27 |
public string $path = '(?P<id>\d+)'; |
| 28 |
|
| 29 |
public function get_methods(): array { |
| 30 |
return [ 'GET' ]; |
| 31 |
} |
| 32 |
|
| 33 |
public function get_name(): string { |
| 34 |
return 'get-scan'; |
| 35 |
} |
| 36 |
|
| 37 |
protected function sanitize_fields(): array { |
| 38 |
return [ |
| 39 |
'id' => Sanitizer::absint(), |
| 40 |
]; |
| 41 |
} |
| 42 |
|
| 43 |
public function GET(): WP_REST_Response { |
| 44 |
try { |
| 45 |
$error = $this->verify_capability(); |
| 46 |
|
| 47 |
if ( $error ) { |
| 48 |
return $error; |
| 49 |
} |
| 50 |
|
| 51 |
$scan_id = (int) $this->params['id']; |
| 52 |
$row = Scan_Entry::find_by_id( $scan_id ); |
| 53 |
|
| 54 |
if ( ! $row ) { |
| 55 |
return $this->respond_error_json( [ |
| 56 |
'message' => esc_html__( 'Scan not found', 'cookiez' ), |
| 57 |
'code' => 'scan_not_found', |
| 58 |
], 404 ); |
| 59 |
} |
| 60 |
|
| 61 |
$scan = ( new Scanner() )->refresh_scan( $scan_id ); |
| 62 |
|
| 63 |
return $this->respond_success_json( [ |
| 64 |
'scan' => $scan->to_array(), |
| 65 |
] ); |
| 66 |
} catch ( Scan_Transport_Exception $ste ) { |
| 67 |
return $this->respond_error_json( [ |
| 68 |
'message' => esc_html__( 'Scan service unavailable', 'cookiez' ), |
| 69 |
'code' => 'scan_service_unavailable', |
| 70 |
], 502 ); |
| 71 |
} catch ( Scan_Service_Client_Exception $ssce ) { |
| 72 |
Logger::error( $ssce->getMessage() ); |
| 73 |
|
| 74 |
return $this->respond_error_json( [ |
| 75 |
'message' => $ssce->getMessage(), |
| 76 |
'code' => 'scan_service_error', |
| 77 |
], 400 ); |
| 78 |
} catch ( Throwable $t ) { |
| 79 |
return $this->respond_error_json( [ |
| 80 |
'message' => $t->getMessage(), |
| 81 |
'code' => 'internal_server_error', |
| 82 |
], 500 ); |
| 83 |
} |
| 84 |
} |
| 85 |
} |
| 86 |
|