| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132 |
- <?php
- namespace Longyi\Feishu\Messages;
- /**
- * 构造飞书交互卡片。
- *
- * 卡片比纯文本贵不了多少,但值班的人一眼就能看到订单号、金额和原因,
- * 并且能直接点进后台,所以告警统一走卡片。
- */
- class AlertCard
- {
- protected array $fields = [];
- protected ?string $description = null;
- protected ?string $buttonUrl = null;
- protected ?string $buttonText = null;
- protected ?string $footer = null;
- public function __construct(
- protected string $title,
- protected string $color = 'red',
- ) {}
- public static function make(string $title, string $color = 'red'): static
- {
- return new static($title, $color);
- }
- /**
- * 正文首段,一般写这条告警发生了什么、需要人做什么。
- */
- public function description(?string $description): static
- {
- $this->description = $description;
- return $this;
- }
- /**
- * 追加一个「字段名: 值」。值为空时自动跳过,避免卡片出现空行。
- */
- public function field(string $label, mixed $value): static
- {
- if ($value === null || $value === '') {
- return $this;
- }
- $this->fields[] = ['label' => $label, 'value' => (string) $value];
- return $this;
- }
- public function button(?string $text, ?string $url): static
- {
- if ($text && $url) {
- $this->buttonText = $text;
- $this->buttonUrl = $url;
- }
- return $this;
- }
- public function footer(?string $footer): static
- {
- $this->footer = $footer;
- return $this;
- }
- /**
- * 输出可直接 POST 给 webhook 的消息体。
- */
- public function toMessage(): array
- {
- $elements = [];
- if ($this->description) {
- $elements[] = [
- 'tag' => 'div',
- 'text' => ['tag' => 'lark_md', 'content' => $this->description],
- ];
- }
- if ($this->fields) {
- $elements[] = [
- 'tag' => 'div',
- 'fields' => array_map(fn (array $field) => [
- 'is_short' => true,
- 'text' => [
- 'tag' => 'lark_md',
- 'content' => "**{$field['label']}**\n{$field['value']}",
- ],
- ], $this->fields),
- ];
- }
- if ($this->buttonUrl) {
- $elements[] = [
- 'tag' => 'action',
- 'actions' => [[
- 'tag' => 'button',
- 'text' => ['tag' => 'plain_text', 'content' => $this->buttonText],
- 'url' => $this->buttonUrl,
- 'type' => 'primary',
- ]],
- ];
- }
- if ($this->footer) {
- $elements[] = [
- 'tag' => 'note',
- 'elements' => [['tag' => 'plain_text', 'content' => $this->footer]],
- ];
- }
- return [
- 'msg_type' => 'interactive',
- 'card' => [
- 'config' => ['wide_screen_mode' => true],
- 'header' => [
- 'template' => $this->color,
- 'title' => ['tag' => 'plain_text', 'content' => $this->title],
- ],
- 'elements' => $elements,
- ],
- ];
- }
- }
|