Completed
Branch 1707_add_explain_command (e87963)
by Alessandro
08:07
created

ExplainQueryService   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 3
c 0
b 0
f 0
lcom 1
cbo 4
dl 0
loc 62
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A execute() 0 16 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
    public function __construct(ClientRegistry $clientRegistry)
42
    {
43
44
        $this->clientRegistry = $clientRegistry;
45
    }
46
47
    /**
48
     * Execute the operation.
49
     *
50
     * @param Query  $query
51
     * @param string $verbosity
52
     *
53
     * @return Cursor
54
     */
55
    public function execute(Query $query, string $verbosity = self::VERBOSITY_ALL_PLAN_EXECUTION): Cursor
56
    {
57
        if (!in_array($query->getMethod(), self::$acceptedMethods)) {
58
            throw new \InvalidArgumentException(
59
                'Cannot explain the method \''.$query->getMethod().'\'. Allowed methods: '. implode(', ',self::$acceptedMethods)
60
            );
61
        };
62
63
        $manager = $this->clientRegistry->getClient($query->getClient())->getManager();
64
65
        return $manager
66
            ->executeCommand(
67
                $query->getDatabase(),
68
                new Command(ExplainCommandBuilder::createCommandArgs($query, $verbosity))
69
            );
70
    }
71
}
72