QueryLogger::getStatements()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Neo4j\Neo4jBundle\Collector;
6
7
use GraphAware\Bolt\Result\Result;
8
use GraphAware\Common\Cypher\StatementInterface;
9
use GraphAware\Common\Result\StatementResult as StatementResultInterface;
10
use GraphAware\Common\Result\StatementStatisticsInterface;
11
use GraphAware\Neo4j\Client\Exception\Neo4jExceptionInterface;
12
13
/**
14
 * @author Xavier Coureau <[email protected]>
15
 */
16
class QueryLogger implements \Countable
17
{
18
    /**
19
     * @var int
20
     */
21
    private $nbQueries = 0;
22
23
    /**
24
     * @var array
25
     */
26
    private $statements = [];
27
28
    /**
29
     * @var array
30
     */
31
    private $statementsHash = [];
32
33
    /**
34
     * @param StatementInterface $statement
35
     */
36
    public function record(StatementInterface $statement)
37
    {
38
        $statementText = $statement->text();
39
        $statementParams = json_encode($statement->parameters());
40
        $tag = $statement->getTag() ?: -1;
41
42
        // Make sure we do not record the same statement twice
43
        if (isset($this->statementsHash[$statementText][$statementParams][$tag])) {
44
            return;
45
        }
46
47
        $idx = $this->nbQueries++;
48
        $this->statements[$idx] = [
49
            'start_time' => microtime(true) * 1000,
50
            'query' => $statementText,
51
            'parameters' => $statementParams,
52
            'tag' => $statement->getTag(),
53
54
            // Add dummy data in case we never run logException or finish
55
            'end_time' => microtime(true) * 1000, // same
56
            'nb_results' => 0,
57
            'statistics' => [],
58
            'scheme' => '',
59
            'success' => false,
60
            'exceptionCode' => 0,
61
            'exceptionMessage' => '',
62
        ];
63
        $this->statementsHash[$statementText][$statementParams][$tag] = $idx;
64
    }
65
66
    /**
67
     * @param StatementResultInterface $statementResult
68
     */
69
    public function finish(StatementResultInterface $statementResult)
70
    {
71
        $scheme = 'Http';
72
        if ($statementResult instanceof Result) {
73
            $scheme = 'Bolt';
74
        }
75
76
        $statement = $statementResult->statement();
77
        $statementText = $statement->text();
78
        $statementParams = $statement->parameters();
79
        $encodedParameters = json_encode($statementParams);
80
        $tag = $statement->getTag() ?: -1;
81
82
        if (!isset($this->statementsHash[$statementText][$encodedParameters][$tag])) {
83
            $idx = $this->nbQueries++;
84
            $this->statements[$idx]['start_time'] = null;
85
            $this->statementsHash[$idx] = $idx;
86
        } else {
87
            $idx = $this->statementsHash[$statementText][$encodedParameters][$tag];
88
        }
89
90
        $this->statements[$idx] = array_merge($this->statements[$idx], [
91
            'end_time' => microtime(true) * 1000,
92
            'nb_results' => $statementResult->size(),
93
            'statistics' => $this->statisticsToArray($statementResult->summarize()->updateStatistics()),
94
            'scheme' => $scheme,
95
            'success' => true,
96
        ]);
97
    }
98
99
    public function reset()
100
    {
101
        $this->nbQueries = 0;
102
        $this->statements = [];
103
        $this->statementsHash = [];
104
    }
105
106
    /**
107
     * @param Neo4jExceptionInterface $exception
108
     */
109
    public function logException(Neo4jExceptionInterface $exception)
110
    {
111
        $idx = $this->nbQueries - 1;
112
        $this->statements[$idx] = array_merge($this->statements[$idx], [
113
            'end_time' => microtime(true) * 1000,
114
            'exceptionCode' => method_exists($exception, 'classification') ? $exception->classification() : '',
115
            'exceptionMessage' => method_exists($exception, 'getMessage') ? $exception->getMessage() : '',
116
            'success' => false,
117
        ]);
118
    }
119
120
    /**
121
     * {@inheritdoc}
122
     */
123
    public function count()
124
    {
125
        return $this->nbQueries;
126
    }
127
128
    /**
129
     * @return array[]
130
     */
131
    public function getStatements()
132
    {
133
        return $this->statements;
134
    }
135
136
    /**
137
     * @return array
138
     */
139
    public function getStatementsHash()
140
    {
141
        return $this->statementsHash;
142
    }
143
144
    /**
145
     * @return int
146
     */
147
    public function getElapsedTime()
148
    {
149
        $time = 0;
150
151
        foreach ($this->statements as $statement) {
152
            if (!isset($statement['start_time'], $statement['end_time'])) {
153
                continue;
154
            }
155
156
            $time += $statement['end_time'] - $statement['start_time'];
157
        }
158
159
        return $time;
160
    }
161
162
    private function statisticsToArray(?StatementStatisticsInterface $statementStatistics)
163
    {
164
        if (!$statementStatistics) {
165
            return [];
166
        }
167
        $data = [
168
            'contains_updates' => $statementStatistics->containsUpdates(),
169
            'nodes_created' => $statementStatistics->nodesCreated(),
170
            'nodes_deleted' => $statementStatistics->nodesDeleted(),
171
            'relationships_created' => $statementStatistics->relationshipsCreated(),
172
            'relationships_deleted' => $statementStatistics->relationshipsDeleted(),
173
            'properties_set' => $statementStatistics->propertiesSet(),
174
            'labels_added' => $statementStatistics->labelsAdded(),
175
            'labels_removed' => $statementStatistics->labelsRemoved(),
176
            'indexes_added' => $statementStatistics->indexesAdded(),
177
            'indexes_removed' => $statementStatistics->indexesRemoved(),
178
            'constraints_added' => $statementStatistics->constraintsAdded(),
179
            'constraints_removed' => $statementStatistics->constraintsRemoved(),
180
        ];
181
182
        return $data;
183
    }
184
}
185