Completed
Branch 1707_add_explain_command (6d7b74)
by Alessandro
02:20
created

ExplainQueryService::execute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 8
cts 8
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 9
nc 2
nop 2
crap 2
1
<?php
2
3
namespace Facile\MongoDbBundle\Services\Explain;
4
5
use Facile\MongoDbBundle\Models\Query;
6
use Facile\MongoDbBundle\Services\ClientRegistry;
7
use MongoDB\Driver\Command;
8
use MongoDB\Driver\Cursor;
9
10
class ExplainQueryService
11
{
12
    const VERBOSITY_QUERY_PLANNER = 'queryPlanner';
13
    const VERBOSITY_EXECUTION_STATS = 'executionStats';
14
    const VERBOSITY_ALL_PLAN_EXECUTION = 'allPlansExecution';
15
16
    public static $acceptedMethods= [
17
        'count',
18
        'distinct',
19
        'find',
20
        'findOne',
21
        'findOneAndUpdate',
22
        'findOneAndDelete',
23
        'deleteOne',
24
        'deleteMany',
25
        'aggregate',
26
    ];
27
28
    /** @var ClientRegistry */
29
    private $clientRegistry;
30
31
    /**
32
     * Constructs a explain command.
33
     *
34
     * Supported options:
35
     * verbosity : queryPlanner | executionStats Mode | allPlansExecution (default)
36
     * The explain command provides information on the execution of the following commands:
37
     * count, distinct, group, find, findAndModify, delete, and update.
38
     *
39
     * @param ClientRegistry $clientRegistry
40
     */
41 4
    public function __construct(ClientRegistry $clientRegistry)
42
    {
43 4
        $this->clientRegistry = $clientRegistry;
44 4
    }
45
46
    /**
47
     * Execute the operation.
48
     *
49
     * @param Query  $query
50
     * @param string $verbosity
51
     *
52
     * @return Cursor
53
     */
54 4
    public function execute(Query $query, string $verbosity = self::VERBOSITY_ALL_PLAN_EXECUTION): Cursor
55
    {
56 4
        if (!in_array($query->getMethod(), self::$acceptedMethods)) {
57 2
            throw new \InvalidArgumentException(
58 2
                'Cannot explain the method \''.$query->getMethod().'\'. Allowed methods: '. implode(', ',self::$acceptedMethods)
59
            );
60
        };
61
62 2
        $manager = $this->clientRegistry->getClient($query->getClient())->__debugInfo()['manager'];
63
64
        return $manager
65 2
            ->executeCommand(
66 2
                $query->getDatabase(),
67 2
                new Command(ExplainCommandBuilder::createCommandArgs($query, $verbosity))
68
            );
69
    }
70
}
71
72