|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Binarcode\LaravelDeveloper\Notifications; |
| 4 | + |
| 5 | +use Binarcode\LaravelDeveloper\Dtos\DevNotificationDto; |
| 6 | +use Binarcode\LaravelDeveloper\Models\ExceptionLog; |
| 7 | +use Illuminate\Support\Collection; |
| 8 | +use Illuminate\Support\Facades\Notification as NotificationFacade; |
| 9 | +use Throwable; |
| 10 | + |
| 11 | +class Slack |
| 12 | +{ |
| 13 | + /** |
| 14 | + * @var callable |
| 15 | + */ |
| 16 | + public static $notifyUsing; |
| 17 | + |
| 18 | + protected Collection $queue; |
| 19 | + |
| 20 | + protected bool $persist = false; |
| 21 | + |
| 22 | + public function __construct($args = null) |
| 23 | + { |
| 24 | + $this->queue = collect($args)->flatten(); |
| 25 | + } |
| 26 | + |
| 27 | + public static function make(...$args) |
| 28 | + { |
| 29 | + return new static($args); |
| 30 | + } |
| 31 | + |
| 32 | + public function __destruct() |
| 33 | + { |
| 34 | + $this->queue->each(function ($item) { |
| 35 | + $this->send($item); |
| 36 | + }); |
| 37 | + } |
| 38 | + |
| 39 | + public function persist($persist = true): self |
| 40 | + { |
| 41 | + $this->persist = $persist; |
| 42 | + |
| 43 | + return $this; |
| 44 | + } |
| 45 | + |
| 46 | + private function send($item) |
| 47 | + { |
| 48 | + /** |
| 49 | + * @var string $class |
| 50 | + */ |
| 51 | + $class = config('developer.notification', DevNotification::class); |
| 52 | + |
| 53 | + $dto = new DevNotificationDto; |
| 54 | + |
| 55 | + if ($item instanceof Throwable) { |
| 56 | + if ($this->persist) { |
| 57 | + ExceptionLog::makeFromException($item)->save(); |
| 58 | + } |
| 59 | + |
| 60 | + $dto->setException($item); |
| 61 | + } |
| 62 | + |
| 63 | + if (is_string($item)) { |
| 64 | + $dto->setMessage($item); |
| 65 | + } |
| 66 | + |
| 67 | + if ($item instanceof ExceptionLog) { |
| 68 | + if ($this->persist) { |
| 69 | + $item->save(); |
| 70 | + } |
| 71 | + |
| 72 | + $dto = $dto::makeFromExceptionLog($item); |
| 73 | + } |
| 74 | + |
| 75 | + $notification = new $class($dto); |
| 76 | + |
| 77 | + if (is_callable($cb = static::$notifyUsing)) { |
| 78 | + return call_user_func($cb, $notification); |
| 79 | + } |
| 80 | + |
| 81 | + NotificationFacade::route('slack', config('developer.slack_dev_hook'))->notify( |
| 82 | + $notification |
| 83 | + ); |
| 84 | + |
| 85 | + return $this; |
| 86 | + } |
| 87 | + |
| 88 | + public static function notifyUsing(?callable $notificator) |
| 89 | + { |
| 90 | + Slack::$notifyUsing = $notificator; |
| 91 | + } |
| 92 | +} |
0 commit comments