|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace RESTAPI\Models; |
| 4 | + |
| 5 | +use RESTAPI\Core\Command; |
| 6 | +use RESTAPI\Core\Model; |
| 7 | +use RESTAPI\Fields\IntegerField; |
| 8 | +use RESTAPI\Fields\StringField; |
| 9 | + |
| 10 | +/** |
| 11 | + * Defines a Model for running ping diagnostics from pfSense. |
| 12 | + */ |
| 13 | +class Ping extends Model { |
| 14 | + public StringField $host; |
| 15 | + public IntegerField $count; |
| 16 | + public StringField $source_address; |
| 17 | + public StringField $output; |
| 18 | + public IntegerField $result_code; |
| 19 | + |
| 20 | + public function __construct(mixed $id = null, mixed $parent_id = null, mixed $data = [], mixed ...$options) { |
| 21 | + # Define Model attributes |
| 22 | + $this->verbose_name = 'Ping'; |
| 23 | + |
| 24 | + # Define Model Fields |
| 25 | + $this->host = new StringField( |
| 26 | + required: true, |
| 27 | + write_only: true, |
| 28 | + help_text: 'The IP address or hostname to ping.', |
| 29 | + ); |
| 30 | + $this->count = new IntegerField( |
| 31 | + default: 3, |
| 32 | + minimum: 1, |
| 33 | + maximum: 10, |
| 34 | + write_only: true, |
| 35 | + help_text: 'The number of ping requests to send.', |
| 36 | + ); |
| 37 | + $this->source_address = new StringField( |
| 38 | + default: '', |
| 39 | + allow_empty: true, |
| 40 | + write_only: true, |
| 41 | + help_text: 'The source IP address to use for ping requests.', |
| 42 | + ); |
| 43 | + $this->output = new StringField( |
| 44 | + allow_null: true, |
| 45 | + read_only: true, |
| 46 | + help_text: 'The output from the ping command.', |
| 47 | + ); |
| 48 | + $this->result_code = new IntegerField( |
| 49 | + allow_null: true, |
| 50 | + read_only: true, |
| 51 | + help_text: 'The result code from the ping command. 0 indicates success.', |
| 52 | + ); |
| 53 | + |
| 54 | + parent::__construct($id, $parent_id, $data, ...$options); |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Execute the ping command and populate the output. |
| 59 | + */ |
| 60 | + public function _create(): void { |
| 61 | + # Build the ping command |
| 62 | + $host = escapeshellarg($this->host->value); |
| 63 | + $count = intval($this->count->value); |
| 64 | + $cmd_str = "ping -c {$count}"; |
| 65 | + |
| 66 | + # Add source address if specified |
| 67 | + if (!empty($this->source_address->value)) { |
| 68 | + $source = escapeshellarg($this->source_address->value); |
| 69 | + $cmd_str .= " -S {$source}"; |
| 70 | + } |
| 71 | + |
| 72 | + $cmd_str .= " {$host}"; |
| 73 | + |
| 74 | + # Execute the command |
| 75 | + $cmd = new Command($cmd_str); |
| 76 | + $this->output->value = $cmd->output; |
| 77 | + $this->result_code->value = $cmd->result_code; |
| 78 | + } |
| 79 | +} |
0 commit comments