File: SharedEventManagerTest.php

package info (click to toggle)
php-zend-eventmanager 3.15.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 948 kB
  • sloc: php: 3,543; xml: 749; makefile: 17
file content (333 lines) | stat: -rw-r--r-- 12,522 bytes parent folder | download
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
<?php

declare(strict_types=1);

namespace LaminasTest\EventManager;

use Closure;
use Laminas\EventManager\EventInterface;
use Laminas\EventManager\Exception;
use Laminas\EventManager\SharedEventManager;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;

use function array_shift;
use function sprintf;
use function var_export;

final class SharedEventManagerTest extends TestCase
{
    private Closure $callback;
    private SharedEventManager $manager;

    protected function setUp(): void
    {
        $this->callback = static function (): void {
        };
        $this->manager  = new SharedEventManager();
    }

    /**
     * @param string|EventInterface $event
     * @return callable[]
     */
    public function getListeners(
        SharedEventManager $manager,
        array $identifiers,
        $event,
        int $priority = 1
    ): array {
        $priority  = (int) $priority;
        $listeners = $manager->getListeners($identifiers, $event);
        if (! isset($listeners[$priority])) {
            return [];
        }
        return $listeners[$priority];
    }

    /** @return array<string, array{0: mixed}> */
    public static function invalidIdentifiers(): array
    {
        return [
            'null'                   => [null],
            'true'                   => [true],
            'false'                  => [false],
            'zero'                   => [0],
            'int'                    => [1],
            'zero-float'             => [0.0],
            'float'                  => [1.1],
            'empty-string'           => [''],
            'array'                  => [['test', 'foo']],
            'non-traversable-object' => [(object) ['foo' => 'bar']],
        ];
    }

    /**
     * @param mixed $identifier
     */
    #[DataProvider('invalidIdentifiers')]
    public function testAttachRaisesExceptionForInvalidIdentifer($identifier)
    {
        $this->expectException(Exception\InvalidArgumentException::class);
        $this->expectExceptionMessage('identifier');
        $this->manager->attach($identifier, 'foo', $this->callback);
    }

    /** @psalm-return array<string, array{0: mixed}> */
    public static function invalidEventNames(): array
    {
        return [
            'null'                   => [null],
            'true'                   => [true],
            'false'                  => [false],
            'zero'                   => [0],
            'int'                    => [1],
            'zero-float'             => [0.0],
            'float'                  => [1.1],
            'empty-string'           => [''],
            'array'                  => [['foo', 'bar']],
            'non-traversable-object' => [(object) ['foo' => 'bar']],
        ];
    }

    /**
     * @param mixed $event
     */
    #[DataProvider('invalidEventNames')]
    public function testAttachRaisesExceptionForInvalidEvent($event)
    {
        $this->expectException(Exception\InvalidArgumentException::class);
        $this->expectExceptionMessage('event');
        $this->manager->attach('foo', $event, $this->callback);
    }

    public function testCanAttachToSharedManager(): void
    {
        $this->manager->attach('IDENTIFIER', 'EVENT', $this->callback);

        $listeners = $this->getListeners($this->manager, ['IDENTIFIER'], 'EVENT');
        self::assertSame([$this->callback], $listeners);
    }

    /** @psalm-return array<string, array{0: null|string, 1: null|string}> */
    public static function detachIdentifierAndEvent(): array
    {
        return [
            'null-identifier-and-null-event' => [null, null],
            'same-identifier-and-null-event' => ['IDENTIFIER', null],
            'null-identifier-and-same-event' => [null, 'EVENT'],
            'same-identifier-and-same-event' => ['IDENTIFIER', 'EVENT'],
        ];
    }

    #[DataProvider('detachIdentifierAndEvent')]
    public function testCanDetachFromSharedManagerUsingIdentifierAndEvent(?string $identifier, ?string $event)
    {
        $this->manager->attach('IDENTIFIER', 'EVENT', $this->callback);
        $this->manager->detach($this->callback, $identifier, $event);
        $listeners = $this->getListeners($this->manager, ['IDENTIFIER'], 'EVENT');
        self::assertSame([], $listeners);
    }

    public function testDetachDoesNothingIfIdentifierNotInManager(): void
    {
        $this->manager->attach('IDENTIFIER', 'EVENT', $this->callback);
        $this->manager->detach($this->callback, 'DIFFERENT-IDENTIFIER');

        $listeners = $this->getListeners($this->manager, ['IDENTIFIER'], 'EVENT');
        self::assertSame([$this->callback], $listeners);
    }

    public function testDetachDoesNothingIfIdentifierDoesNotContainEvent(): void
    {
        $this->manager->attach('IDENTIFIER', 'EVENT', $this->callback);
        $this->manager->detach($this->callback, 'IDENTIFIER', 'DIFFERENT-EVENT');
        $listeners = $this->getListeners($this->manager, ['IDENTIFIER'], 'EVENT');
        self::assertSame([$this->callback], $listeners);
    }

    public function testWhenEventIsProvidedAndNoListenersFoundForIdentiferGetListenersWillReturnEmptyList(): void
    {
        $test = $this->manager->getListeners(['IDENTIFIER'], 'EVENT');
        self::assertIsArray($test);
        self::assertCount(0, $test);
    }

    public function testWhenEventIsProvidedGetListenersReturnsAllListenersIncludingWildcardListeners(): void
    {
        $callback1 = clone $this->callback;
        $callback2 = clone $this->callback;
        $callback3 = clone $this->callback;
        $callback4 = clone $this->callback;

        $this->manager->attach('IDENTIFIER', 'EVENT', $callback1);
        $this->manager->attach('IDENTIFIER', '*', $callback2);
        $this->manager->attach('*', 'EVENT', $callback3);
        $this->manager->attach('IDENTIFIER', 'EVENT', $callback4);

        $test = $this->getListeners($this->manager, ['IDENTIFIER'], 'EVENT');
        self::assertEquals([
            $callback1,
            $callback4,
            $callback2,
            $callback3,
        ], $test);
    }

    public function testClearListenersWhenNoEventIsProvidedRemovesAllListenersForTheIdentifier(): void
    {
        $wildcardIdentifier = clone $this->callback;
        $this->manager->attach('IDENTIFIER', 'EVENT', $this->callback);
        $this->manager->attach('IDENTIFIER', '*', $this->callback);
        $this->manager->attach('*', 'EVENT', $wildcardIdentifier);
        $this->manager->attach('IDENTIFIER', 'EVENT', $this->callback);

        $this->manager->clearListeners('IDENTIFIER');

        $listeners = $this->getListeners($this->manager, ['IDENTIFIER'], 'EVENT');
        self::assertSame(
            [$wildcardIdentifier],
            $listeners,
            sprintf(
                'Listener list should contain only wildcard identifier listener; received: %s',
                var_export($listeners, true)
            )
        );
    }

    public function testClearListenersRemovesAllExplicitListenersForGivenIdentifierAndEvent(): void
    {
        $alternate = clone $this->callback;
        $wildcard  = clone $this->callback;
        $this->manager->attach('IDENTIFIER', 'EVENT', $this->callback);
        $this->manager->attach('IDENTIFIER', 'ALTERNATE', $alternate);
        $this->manager->attach('*', 'EVENT', $wildcard);
        $this->manager->attach('IDENTIFIER', 'EVENT', $this->callback);

        $this->manager->clearListeners('IDENTIFIER', 'EVENT');

        $listeners = $this->getListeners($this->manager, ['IDENTIFIER'], 'EVENT');
        self::assertIsArray($listeners, 'Unexpected return value from getListeners() for event EVENT');
        self::assertCount(1, $listeners);
        $listener = array_shift($listeners);
        self::assertSame($wildcard, $listener, sprintf(
            'Expected only wildcard listener on event EVENT after clearListener operation; received: %s',
            var_export($listener, true)
        ));

        $listeners = $this->getListeners($this->manager, ['IDENTIFIER'], 'ALTERNATE');
        self::assertIsArray(
            $listeners,
            'Unexpected return value from getListeners() for event ALTERNATE'
        );
        self::assertCount(1, $listeners);
        $listener = array_shift($listeners);
        self::assertSame($alternate, $listener, 'Unexpected listener list for event ALTERNATE');
    }

    public function testClearListenersDoesNotRemoveWildcardListenersWhenEventIsProvided(): void
    {
        $wildcardEventListener      = clone $this->callback;
        $wildcardIdentifierListener = clone $this->callback;
        $this->manager->attach('IDENTIFIER', 'EVENT', $this->callback);
        $this->manager->attach('IDENTIFIER', '*', $wildcardEventListener);
        $this->manager->attach('*', 'EVENT', $wildcardIdentifierListener);
        $this->manager->attach('IDENTIFIER', 'EVENT', $this->callback);

        $this->manager->clearListeners('IDENTIFIER', 'EVENT');

        $listeners = $this->getListeners($this->manager, ['IDENTIFIER'], 'EVENT');
        self::assertContains(
            $wildcardEventListener,
            $listeners,
            'Event listener list after clear operation does not include wildcard event listener'
        );
        self::assertContains(
            $wildcardIdentifierListener,
            $listeners,
            'Event listener list after clear operation does not include wildcard identifier listener'
        );
        self::assertNotContains(
            $this->callback,
            $listeners,
            'Event listener list after clear operation includes explicitly attached listener and should not'
        );
    }

    public function testClearListenersDoesNothingIfNoEventsRegisteredForIdentifier(): void
    {
        $callback = clone $this->callback;
        $this->manager->attach('IDENTIFIER', 'NOTEVENT', $this->callback);
        $this->manager->attach('*', 'EVENT', $this->callback);

        $this->manager->clearListeners('IDENTIFIER', 'EVENT');

        // getListeners() always pulls in wildcard listeners
        self::assertEquals([
            1 => [
                $this->callback,
            ],
        ], $this->manager->getListeners(['IDENTIFIER'], 'EVENT'));
    }

    /** @psalm-return array<string, array{0: mixed}> */
    public static function invalidIdentifiersAndEvents(): array
    {
        $types = self::invalidIdentifiers();
        unset($types['null']);
        return $types;
    }

    /**
     * @param mixed $identifier
     */
    #[DataProvider('invalidIdentifiersAndEvents')]
    public function testDetachingWithInvalidIdentifierTypeRaisesException($identifier)
    {
        $this->expectException(Exception\InvalidArgumentException::class);
        $this->expectExceptionMessage('Invalid identifier');
        $this->manager->detach($this->callback, $identifier, 'test');
    }

    /**
     * @param mixed $eventName
     */
    #[DataProvider('invalidIdentifiersAndEvents')]
    public function testDetachingWithInvalidEventTypeRaisesException($eventName)
    {
        $this->manager->attach('IDENTIFIER', '*', $this->callback);
        $this->expectException(Exception\InvalidArgumentException::class);
        $this->expectExceptionMessage('Invalid event name');
        $this->manager->detach($this->callback, 'IDENTIFIER', $eventName);
    }

    /** @psalm-return array<string, array{0: mixed}> */
    public static function invalidListenersAndEventNamesForFetchingListeners(): array
    {
        $events             = self::invalidIdentifiers();
        $events['wildcard'] = ['*'];
        return $events;
    }

    /**
     * @param mixed $eventName
     */
    #[DataProvider('invalidListenersAndEventNamesForFetchingListeners')]
    public function testGetListenersRaisesExceptionForInvalidEventName($eventName)
    {
        $this->expectException(Exception\InvalidArgumentException::class);
        $this->expectExceptionMessage('non-empty, non-wildcard');
        $this->manager->getListeners(['IDENTIFIER'], $eventName);
    }

    /**
     * @param mixed $identifier
     */
    #[DataProvider('invalidListenersAndEventNamesForFetchingListeners')]
    public function testGetListenersRaisesExceptionForInvalidIdentifier($identifier)
    {
        $this->expectException(Exception\InvalidArgumentException::class);
        $this->expectExceptionMessage('non-empty, non-wildcard');
        $this->manager->getListeners([$identifier], 'EVENT');
    }
}