1<?php
2
3namespace dokuwiki\plugin\slacknotifier\event;
4
5use InvalidArgumentException;
6
7/**
8 * @property string $changeType
9 * @property string|null $summary
10 * @property string $id
11 * @property int|false $oldRevision
12 * @property int $newRevision
13 * @link https://www.dokuwiki.org/devel:event:common_wikipage_save
14 */
15class PageSaveEvent extends BaseEvent
16{
17    const TYPE_RENAME = 'rename';
18
19    private const EVENT_TYPE = [
20        DOKU_CHANGE_TYPE_EDIT => 'edit',
21        DOKU_CHANGE_TYPE_MINOR_EDIT => 'edit minor',
22        DOKU_CHANGE_TYPE_CREATE => 'create',
23        DOKU_CHANGE_TYPE_DELETE => 'delete',
24        self::TYPE_RENAME => 'rename',
25    ];
26
27    public function getEventType(): ?string
28    {
29        return self::EVENT_TYPE[$this->changeType] ?? null;
30    }
31
32    /**
33     * Root namespace of the page.
34     */
35    public function getNamespace(): string
36    {
37        // Handle special case of page being in root namespace
38        $pos = strpos($this->id, ':');
39        if ($pos === false) {
40            return ':';
41        }
42
43        return explode(':', $this->id, 2)[0];
44    }
45
46    public function isCreate(): bool
47    {
48        return $this->changeType === DOKU_CHANGE_TYPE_CREATE;
49    }
50
51    public function isDelete(): bool
52    {
53        return $this->changeType === DOKU_CHANGE_TYPE_DELETE;
54    }
55
56    public function convertToRename(PageSaveEvent $deleteEvent)
57    {
58        // Sanity check
59        if (
60            !$this->isCreate() ||
61            !$deleteEvent->isDelete() ||
62            $this->summary !== $deleteEvent->summary
63        ) {
64            throw new InvalidArgumentException("Unexpected event");
65        }
66
67        $this->changeType = self::TYPE_RENAME;
68        $this->oldRevision = $deleteEvent->oldRevision;
69    }
70}
71