CommandObserver.php 1.48 KB
Newer Older
1 2 3 4
<?php

namespace MongoDB\Tests;

5
use Exception;
6 7 8
use MongoDB\Driver\Monitoring\CommandFailedEvent;
use MongoDB\Driver\Monitoring\CommandStartedEvent;
use MongoDB\Driver\Monitoring\CommandSubscriber;
9 10 11 12
use MongoDB\Driver\Monitoring\CommandSucceededEvent;
use function call_user_func;
use function MongoDB\Driver\Monitoring\addSubscriber;
use function MongoDB\Driver\Monitoring\removeSubscriber;
13 14 15 16 17 18

/**
 * Observes command documents using the driver's monitoring API.
 */
class CommandObserver implements CommandSubscriber
{
19
    /** @var array */
20 21 22 23 24 25
    private $commands = [];

    public function observe(callable $execution, callable $commandCallback)
    {
        $this->commands = [];

26
        addSubscriber($this);
27

28 29
        try {
            call_user_func($execution);
30 31
        } catch (Exception $executionException) {
        }
32

33
        removeSubscriber($this);
34 35 36 37

        foreach ($this->commands as $command) {
            call_user_func($commandCallback, $command);
        }
38 39 40 41

        if (isset($executionException)) {
            throw $executionException;
        }
42 43 44 45
    }

    public function commandStarted(CommandStartedEvent $event)
    {
46
        $this->commands[$event->getRequestId()]['started'] = $event;
47 48 49 50
    }

    public function commandSucceeded(CommandSucceededEvent $event)
    {
51
        $this->commands[$event->getRequestId()]['succeeded'] = $event;
52 53 54 55
    }

    public function commandFailed(CommandFailedEvent $event)
    {
56
        $this->commands[$event->getRequestId()]['failed'] = $event;
57 58
    }
}