Lines 93.75% 15 / 16
Functions and Methods 66.66% 2 / 3
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
TriggerSubscribers 93.75% 15 / 16 66.66% 2 / 3 8.02 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 subscriptionAdded 100.00% 6 / 6 100.00% 1 / 1 3
 subscriptionRemoved 88.88% 8 / 9 0.00% 0 / 1 4.02
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Broker\Trigger;
6
7use Stewart\Runtime\Broker\BrokerSubscription;
8use Stewart\Runtime\Broker\BrokerSubscriptionListener;
9
10// Home Assistant sees each trigger spec once, however many app subscriptions share it.
11final class TriggerSubscribers implements BrokerSubscriptionListener
12{
13    /** @var array<string, int> */
14    private array $subscriberCountsByKey = [];
15
16    public function __construct(private readonly HaTriggerLink $triggers) {}
17
18    public function subscriptionAdded(BrokerSubscription $subscription): void
19    {
20        if ($subscription->trigger === null) {
21            return;
22        }
23
24        $key = $subscription->trigger->getSharingKey();
25        $this->subscriberCountsByKey[$key] = ($this->subscriberCountsByKey[$key] ?? 0) + 1;
26
27        if ($this->subscriberCountsByKey[$key] === 1) {
28            $this->triggers->subscribeTrigger($subscription->trigger);
29        }
30    }
31
32    public function subscriptionRemoved(BrokerSubscription $subscription): void
33    {
34        if ($subscription->trigger === null) {
35            return;
36        }
37
38        $key = $subscription->trigger->getSharingKey();
39
40        if (!isset($this->subscriberCountsByKey[$key])) {
41            return;
42        }
43
44        if (--$this->subscriberCountsByKey[$key] > 0) {
45            return;
46        }
47
48        unset($this->subscriberCountsByKey[$key]);
49        $this->triggers->unsubscribeTrigger($subscription->trigger);
50    }
51}