-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
EventFiredWith.php
105 lines (90 loc) · 2.49 KB
/
EventFiredWith.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
namespace Cake\TestSuite\Constraint;
use Cake\Event\Event;
use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\Constraint\Constraint;
/**
* EventFiredWith constraint
*
* @internal
*/
class EventFiredWith extends Constraint
{
/**
* Array of fired events
*
* @var \Cake\Event\EventManager
*/
protected $_eventManager;
/**
* Event data key
*
* @var string
*/
protected $_dataKey;
/**
* Event data value
*
* @var string
*/
protected $_dataValue;
/**
* Constructor
*
* @param \Cake\Event\EventManager $eventManager Event manager to check
* @param string $dataKey Data key
* @param string $dataValue Data value
*/
public function __construct($eventManager, $dataKey, $dataValue)
{
parent::__construct();
$this->_eventManager = $eventManager;
$this->_dataKey = $dataKey;
$this->_dataValue = $dataValue;
if ($this->_eventManager->getEventList() === null) {
throw new AssertionFailedError('The event manager you are asserting against is not configured to track events.');
}
}
/**
* Checks if event is in fired array
*
* @param mixed $other Constraint check
* @return bool
*/
public function matches($other)
{
$firedEvents = [];
$list = $this->_eventManager->getEventList();
$totalEvents = count($list);
for ($e = 0; $e < $totalEvents; $e++) {
$firedEvents[] = $list[$e];
}
$eventGroup = collection($firedEvents)
->groupBy(function (Event $event) {
return $event->getName();
})
->toArray();
if (!array_key_exists($other, $eventGroup)) {
return false;
}
$events = $eventGroup[$other];
if (count($events) > 1) {
throw new AssertionFailedError(sprintf('Event "%s" was fired %d times, cannot make data assertion', $other, count($events)));
}
/* @var \Cake\Event\Event $event */
$event = $events[0];
if (array_key_exists($this->_dataKey, $event->getData()) === false) {
return false;
}
return $event->getData($this->_dataKey) === $this->_dataValue;
}
/**
* Assertion message string
*
* @return string
*/
public function toString()
{
return 'was fired with ' . $this->_dataKey . ' matching ' . (string)$this->_dataValue;
}
}