aboutsummaryrefslogtreecommitdiffhomepage
path: root/Digitigrade/Model/Notification.php
blob: 50e999186925715640ce158891a81243b72171d8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?php
namespace Digitigrade\Model;

use Digitigrade\Model;
use Digitigrade\Notification\Notifyable;

class Notification extends Model {
    public ?int $id;
    public UserAccount $userAccount;
    public string $itemType;
    public string $itemData;
    public \DateTimeImmutable $created;

    /**
     * Creates a new Notification from a Notifyable object, but does not send it.
     * @param Notifyable $item the item to send in the notification
     * @param UserAccount $user the user to send the notification to
     * @return Notification
     */
    public static function fromNotifyable(Notifyable $item, UserAccount $user): self {
        $notif = new self();
        $notif->userAccount = $user;
        $notif->itemType = $item::class;
        $notif->itemData = json_encode($item->toJsonReference());
        $notif->created = new \DateTimeImmutable();

        $notif->save();
        return $notif;
    }

    public function toNotifyable(): ?Notifyable {
        return $this->itemType::fromJsonReference(json_decode($this->itemData));
    }

    /**
     * Saves this object and delivers the notification to the recipient user.
     * @return void
     */
    public function send() {
        $this->save();
        // TODO: send it via any push mechanisms
    }

    /**
     * @return self[]
     */
    public static function findAllForUser(UserAccount $user, ?int $limit = null, int $offset = 0, ?\DateTimeInterface $since = null) {
        $where = 'user_account = ?';
        $params = [$user->id];
        if (isset($since)) {
            $where .= ' AND created > ?';
            $params[] = $since->format('c');
        }
        return self::findAllWhere($where, $params, $limit, $offset, 'id DESC');
    }

}