friendship ended with social-app. php is my new best friend
at main 2.1 kB view raw
1<?php declare(strict_types = 1); 2 3namespace Contributte\Logging\Slack; 4 5use Contributte\Logging\Exceptions\Runtime\Logger\SlackBadRequestException; 6use Contributte\Logging\ILogger; 7use Contributte\Logging\Slack\Formatter\IFormatter; 8use Contributte\Logging\Slack\Formatter\SlackContext; 9use Nette\Utils\Arrays; 10use Throwable; 11 12final class SlackLogger implements ILogger 13{ 14 15 /** @var mixed[] */ 16 private $config; 17 18 /** @var IFormatter[] */ 19 private $formatters = []; 20 21 /** 22 * @param mixed[] $config 23 */ 24 public function __construct(array $config) 25 { 26 $this->config = $config; 27 } 28 29 public function addFormatter(IFormatter $formatter): void 30 { 31 $this->formatters[] = $formatter; 32 } 33 34 /** 35 * @param mixed $message 36 */ 37 public function log($message, string $priority = ILogger::INFO): void 38 { 39 if (!in_array($priority, [ILogger::ERROR, ILogger::EXCEPTION, ILogger::CRITICAL], true)) { 40 return; 41 } 42 43 if (!($message instanceof Throwable)) { 44 return; 45 } 46 47 $context = new SlackContext($this->config); 48 49 // Apply all formatters 50 foreach ($this->formatters as $formatter) { 51 $context = $formatter->format($context, $message, $priority); 52 } 53 54 // Send to channel 55 $this->makeRequest($context); 56 } 57 58 protected function makeRequest(SlackContext $context): void 59 { 60 $url = $this->get('url'); 61 62 $streamcontext = [ 63 'http' => [ 64 'method' => 'POST', 65 'header' => 'Content-type: application/x-www-form-urlencoded', 66 'timeout' => $this->get('timeout', 30), 67 'content' => http_build_query([ 68 'payload' => json_encode(array_filter($context->toArray())), 69 ]), 70 ], 71 ]; 72 73 $response = @file_get_contents($url, false, stream_context_create($streamcontext)); 74 75 if ($response !== 'ok') { 76 throw new SlackBadRequestException([ 77 'url' => $url, 78 'context' => $streamcontext, 79 'response' => [ 80 'headers' => $http_response_header, 81 ], 82 ]); 83 } 84 } 85 86 /** 87 * @param mixed $default 88 * @return mixed 89 */ 90 protected function get(string $key, $default = null) 91 { 92 return func_num_args() > 1 93 ? Arrays::get($this->config, explode('.', $key), $default) 94 : Arrays::get($this->config, explode('.', $key)); 95 } 96 97}