Passed
Push — master ( 3880dd...1a3c5e )
by Ilario
04:06
created

ExplainQueryService   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 1
Metric Value
eloc 24
dl 0
loc 62
ccs 11
cts 11
cp 1
rs 10
c 2
b 0
f 1
wmc 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A execute() 0 14 2
A __construct() 0 3 1
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
14
    const VERBOSITY_EXECUTION_STATS = 'executionStats';
15
16
    const VERBOSITY_ALL_PLAN_EXECUTION = 'allPlansExecution';
17
18
    public const ACCEPTED_METHODS = [
19
        'count',
20
        'distinct',
21
        'find',
22
        'findOne',
23
        'findOneAndUpdate',
24
        'findOneAndDelete',
25
        'deleteOne',
26
        'deleteMany',
27
        'aggregate',
28
    ];
29
30
    /** @var ClientRegistry */
31
    private $clientRegistry;
32
33
    /**
34
     * Constructs a explain command.
35
     *
36
     * Supported options:
37
     * verbosity : queryPlanner | executionStats Mode | allPlansExecution (default)
38
     * The explain command provides information on the execution of the following commands:
39
     * count, distinct, group, find, findAndModify, delete, and update.
40
     *
41 4
     * @param ClientRegistry $clientRegistry
42
     */
43 4
    public function __construct(ClientRegistry $clientRegistry)
44 4
    {
45
        $this->clientRegistry = $clientRegistry;
46
    }
47
48
    /**
49
     * Execute the operation.
50
     *
51
     * @param Query $query
52
     * @param string $verbosity
53
     *
54
     * @throws \Exception
55
     *
56 4
     * @return Cursor
57
     */
58 4
    public function execute(Query $query, string $verbosity = self::VERBOSITY_ALL_PLAN_EXECUTION): Cursor
59 2
    {
60 2
        if (! \in_array($query->getMethod(), self::ACCEPTED_METHODS, true)) {
61
            throw new \InvalidArgumentException(
62
                'Cannot explain the method \'' . $query->getMethod() . '\'. Allowed methods: ' . implode(', ', self::ACCEPTED_METHODS)
63
            );
64 2
        }
65
66
        $manager = $this->clientRegistry->getClient($query->getClient(), $query->getDatabase())->__debugInfo()['manager'];
67 2
68 2
        return $manager
69 2
            ->executeCommand(
70
                $query->getDatabase(),
71
                new Command(ExplainCommandBuilder::createCommandArgs($query, $verbosity))
72
            );
73
    }
74
}
75