|
| 1 | +<?php |
| 2 | +namespace HelloFresh\Stats\StatsD; |
| 3 | + |
| 4 | +use League\StatsD\Client; |
| 5 | +use League\StatsD\Exception\ConnectionException; |
| 6 | + |
| 7 | +class CachingClient extends Client |
| 8 | +{ |
| 9 | + /** @var resource */ |
| 10 | + protected $socket; |
| 11 | + |
| 12 | + /** |
| 13 | + * @throws ConnectionException |
| 14 | + * @return resource |
| 15 | + */ |
| 16 | + protected function getSocket() |
| 17 | + { |
| 18 | + if (!$this->socket) { |
| 19 | + $this->socket = @fsockopen('udp://' . $this->host, $this->port, $errno, $errstr, $this->timeout); |
| 20 | + if (!$this->socket) { |
| 21 | + throw new ConnectionException($this, '(' . $errno . ') ' . $errstr); |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + return $this->socket; |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * Send Data to StatsD Server |
| 30 | + * @param array $data A list of messages to send to the server |
| 31 | + * @throws ConnectionException If there is a connection problem with the host |
| 32 | + * @return $this |
| 33 | + */ |
| 34 | + protected function send(array $data) |
| 35 | + { |
| 36 | + try { |
| 37 | + $socket = $this->getSocket(); |
| 38 | + $messages = []; |
| 39 | + $prefix = $this->namespace ? $this->namespace . '.' : ''; |
| 40 | + foreach ($data as $key => $value) { |
| 41 | + $messages[] = $prefix . $key . ':' . $value; |
| 42 | + } |
| 43 | + $this->message = implode("\n", $messages); |
| 44 | + @fwrite($socket, $this->message); |
| 45 | + fflush($socket); |
| 46 | + } catch (ConnectionException $e) { |
| 47 | + if ($this->throwConnectionExceptions) { |
| 48 | + throw $e; |
| 49 | + } else { |
| 50 | + trigger_error( |
| 51 | + sprintf('StatsD server connection failed (udp://%s:%d)', $this->host, $this->port), |
| 52 | + E_USER_WARNING |
| 53 | + ); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + return $this; |
| 58 | + } |
| 59 | + |
| 60 | + public function __destruct() |
| 61 | + { |
| 62 | + if ($this->socket) { |
| 63 | + fclose($this->socket); |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments