<?php
 namespace TechSoft\Laravel\Statistics; use Illuminate\Support\Facades\Log; class StatisticsUtil { protected static $timeMap = array(); protected static $client = null; private static $reportAddress = null; public static function init($address) { self::$reportAddress = $address; } public static function tickStart($module, $group) { if (!self::$reportAddress) { return; } return self::$timeMap[$module][$group] = microtime(true); } public static function tickEnd($module, $group, $success = true, $code = 0, $msg = null) { if (!self::$reportAddress) { return; } if (isset(self::$timeMap[$module][$group]) && self::$timeMap[$module][$group] > 0) { $timeStart = self::$timeMap[$module][$group]; self::$timeMap[$module][$group] = 0; } else { $timeStart = microtime(true); } self::send($module, $group, round((microtime(true) - $timeStart) * 1000, 2), $success, $code, $msg); } public static function tick($module, $group, $costMS, $success = true, $code = 0, $msg = null) { if (!self::$reportAddress) { return; } self::send($module, $group, round($costMS, 2), $success, $code, $msg); } private static function send($module, $group, $cost, $success, $code, $msg) { try { $binData = self::encode($module, $group, $cost, $success, $code, $msg); if (extension_loaded('swoole')) { if (!self::$client || !self::$client->isConnected()) { self::$client = new \swoole_client(SWOOLE_UDP); list($ip, $port) = explode(':', self::$reportAddress); self::$client->connect($ip, $port); } self::$client->send($binData); self::$client->close(); self::$client = null; } else { $timeout = null; $socket = stream_socket_client('udp://' . self::$reportAddress, $errno, $errmsg, $timeout); if (!$socket) { return; } stream_set_timeout($socket, $timeout); stream_socket_sendto($socket, $binData); } } catch (\Exception $e) { Log::error('StatisticsUtil.send.error -> ' . $e->getMessage()); } } private static function encode($module, $group, $cost, $success, $code = 0, $msg = '') { $data = array( 'module' => $module, 'group' => $group, 'cost' => $cost, 'success' => $success, 'time' => time(), 'code' => $code, 'msg' => $msg ); $string = json_encode($data); $packData = pack('N', strlen($string)) . $string; return $packData; } }