<?php

namespace App\Helpers\Utility;

use Symfony\Component\Process\Process;

class Pinger {
  
  /**
   * Ping a given IP address.
   */
  static function ping($_ip) {

    if(filter_var($_ip, FILTER_VALIDATE_IP)) {
      $command = new Process(['ping', '-c', '5', $_ip ]);

      $command->run();

      if($command->isSuccessful()) {
        $packet_loss = 0;
        $packet_latency = 0.0;

        $output = $command->getOutput();

        preg_match('/(\d)% packet loss/', $output, $packet_loss);
        preg_match('/\d+.\d+\/(\d+.\d+)\/\d+.\d+\/\d+.\d+/', $output, $packet_latency);
        
        return [100 - floor((float)$packet_loss[1]), $packet_latency[1]];
      }
    }

    return [0, 0];
  }

  static function arping($_src, $_dst) {
    if(filter_var($_src, FILTER_VALIDATE_IP) && filter_var($_dst, FILTER_VALIDATE_IP)) {
      $command = new Process(['arping', '-c', '5', '-S', $_src, $_dst]);

      $command->run();

      if($command->isSuccessful()) {
        $packet_loss = 0;

        if(preg_match('/(\d{1,3})% unanswered/', $command->getOutput(), $packet_loss)) {
          return 100 - (int)$packet_loss[1];
        }
      }
    }

    return 'FAILED';
  }

}

?>