1<?php
2
3namespace dokuwiki\plugin\slacknotifier\helper;
4
5use dokuwiki\plugin\slacknotifier\event\PageSaveEvent;
6
7class Formatter
8{
9    /** @var Config */
10    private $config;
11
12    public function __construct(Config $config)
13    {
14        $this->config = $config;
15    }
16
17    public function format(PageSaveEvent $event, Context $context): array
18    {
19        $actionMap = [
20            'create' => 'created',
21            'edit' => 'updated',
22            'edit minor' => 'updated (minor edit)',
23            'delete' => 'removed',
24            'rename' => 'renamed',
25        ];
26        $eventType = $event->getEventType();
27        $action = $actionMap[$eventType] ?? null;
28        $username = $context->username ?: 'Anonymous';
29        $page = $event->id;
30        $link = $this->buildUrl($page, $event->newRevision);
31        $title = "{$username} {$action} page <{$link}|{$page}>";
32        if ($eventType !== 'delete') {
33            $oldRev = $event->oldRevision;
34            if ($oldRev) {
35                $diffURL = $this->buildUrl($page, $event->newRevision, $event->oldRevision);
36                $title .= " (<{$diffURL}|Compare changes>)";
37            }
38        }
39
40        $formatted = ['text' => $title];
41        if ($event->summary && $this->config->show_summary) {
42            $formatted['attachments'] = [
43                [
44                    'fallback' => 'Change summary',
45                    'title' => 'Summary',
46                    'text' => "{$event->summary}\n- {$username}",
47                ],
48            ];
49        }
50
51        return $formatted;
52    }
53
54    private function buildUrl(string $page, int $rev, ?int $oldRev = null): ?string
55    {
56        $urlParameters = $oldRev ? "do=diff&rev2[0]=$oldRev&rev2[1]=$rev" : "rev=$rev";
57
58        return wl($page, $urlParameters, true, '&');
59    }
60}
61