/
StatsListener.php
65 lines (56 loc) · 1.83 KB
/
StatsListener.php
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
58
59
60
61
62
63
64
65
<?php
declare(strict_types=1);
/**
* StatsListener
*/
namespace Fr3nch13\Stats\Event;
use Cake\Event\Event;
use Cake\Event\EventListenerInterface;
use Cake\ORM\Locator\LocatorAwareTrait;
use Fr3nch13\Stats\Model\Entity\StatsObject;
use Fr3nch13\Stats\Model\Table\StatsObjectsTable;
/**
* Stats Listener
*
* Event listener to add statistics about Ns Issues.
*/
class StatsListener implements EventListenerInterface
{
use LocatorAwareTrait;
/**
* @var \Fr3nch13\Stats\Model\Table\StatsObjectsTable|null
*/
public ?StatsObjectsTable $StatsObjects = null;
/**
* Used to map the event names to their related methods.
*
* @return array<string> The map of event names to methods.
*/
public function implementedEvents(): array
{
return [
'Fr3nch13.Stats.count' => 'recordCount',
];
}
/**
* The main entry point into the Event.
*
* @param \Cake\Event\Event $event The triggered event.
* @param string $key The StatsObject key
* @param int $count The count to register, defaults to 1
* @return \Fr3nch13\Stats\Model\Entity\StatsObject The object with the attached counts, if count > 0
*/
public function recordCount(Event $event, string $key, int $count = 1): StatsObject
{
if (!$this->StatsObjects) {
$config = $this->getTableLocator()->exists('StatsObjects') ? [] : ['className' => StatsObjectsTable::class];
/** @var \Fr3nch13\Stats\Model\Table\StatsObjectsTable $StatsObjects */
$StatsObjects = $this->getTableLocator()->get('StatsObjects', $config);
$this->StatsObjects = $StatsObjects;
}
// either get or create the object.
$object = $this->StatsObjects->register($key, ['count' => $count]);
// record the counts.
return $object;
}
}