Completed
Push — devops/catch-breaking-changes-... ( 88c9a6 )
by Bas
28s queued 18s
created

RunsQueries::runQueryCallback()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 16
ccs 5
cts 5
cp 1
rs 10
cc 2
nc 2
nop 3
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace LaravelFreelancerNL\Aranguent\Concerns;
6
7
use Closure;
8
use Exception;
9
use Iterator;
10
use LaravelFreelancerNL\Aranguent\Query\Builder as QueryBuilder;
11
use LaravelFreelancerNL\Aranguent\QueryException;
12
use LaravelFreelancerNL\FluentAQL\QueryBuilder as ArangoQueryBuilder;
13
use stdClass;
14
15
trait RunsQueries
16
{
17
    /**
18
     * Run a select statement against the database and returns a generator.
19
     * ($useReadPdo is a dummy to adhere to the interface).
20
     *
21
     * @param  string  $query
22
     * @param  array  $bindings
23
     * @param  bool|null  $useReadPdo
24
     * @return Iterator|null
25
     */
26
    public function cursor($query, $bindings = [], $useReadPdo = null): ?Iterator
0 ignored issues
show
Unused Code introduced by
The parameter $useReadPdo is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

26
    public function cursor($query, $bindings = [], /** @scrutinizer ignore-unused */ $useReadPdo = null): ?Iterator

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
27
    {
28
        // Usage of a separate DB to read date isn't supported at this time
29
        $useReadPdo = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $useReadPdo is dead and can be removed.
Loading history...
30
31
        return $this->run($query, $bindings, function ($query, $bindings) {
32
            if ($this->pretending()) {
0 ignored issues
show
Bug introduced by
It seems like pretending() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

32
            if ($this->/** @scrutinizer ignore-call */ pretending()) {
Loading history...
33
                return [];
34
            }
35
36
            $statement = $this->arangoClient->prepare($query, $bindings);
37
38
            return $statement->execute();
39
        });
40
    }
41
42
    /**
43
     * Execute an AQL statement and return the boolean result.
44
     *
45
     * @param string|ArangoQueryBuilder $query
46
     * @param array            $bindings
47
     *
48
     * @return bool
49
     */
50 23
    public function statement($query, $bindings = []): bool
51
    {
52 23
        [$query, $bindings] = $this->handleQueryBuilder(
53
            $query,
54
            $bindings
55
        );
56
57 23
        return $this->run($query, $bindings, function ($query, $bindings) {
58 23
            if ($this->pretending()) {
59
                return true;
60
            }
61
62 23
            $statement = $this->arangoClient->prepare($query, $bindings);
63
64 23
            $statement->execute();
65
66 22
            $affectedDocumentCount = $statement->getWritesExecuted();
67 22
            $this->recordsHaveBeenModified($changed = $affectedDocumentCount > 0);
0 ignored issues
show
Bug introduced by
It seems like recordsHaveBeenModified() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

67
            $this->/** @scrutinizer ignore-call */ 
68
                   recordsHaveBeenModified($changed = $affectedDocumentCount > 0);
Loading history...
68
69 22
            return $changed;
70
        });
71
    }
72
73
    /**
74
     * Run an AQL statement and get the number of rows affected.
75
     *
76
     * @param string|ArangoQueryBuilder $query
77
     * @param array            $bindings
78
     *
79
     * @return int
80
     */
81 35
    public function affectingStatement($query, $bindings = []): int
82
    {
83 35
        [$query, $bindings] = $this->handleQueryBuilder(
84
            $query,
85
            $bindings
86
        );
87
88 35
        return $this->run($query, $bindings, function () use ($query, $bindings) {
89 35
            if ($this->pretending()) {
90
                return 0;
91
            }
92
93
            // For update or delete statements, we want to get the number of rows affected
94
            // by the statement and return that back to the developer. We'll first need
95
            // to execute the statement and get the executed writes from the extra.
96 35
            $statement = $this->arangoClient->prepare($query, $bindings);
97
98 35
            $statement->execute();
99
100 35
            $affectedDocumentCount = $statement->getWritesExecuted();
101
102 35
            $this->recordsHaveBeenModified($affectedDocumentCount > 0);
103
104 35
            return $affectedDocumentCount;
105
        });
106
    }
107
108
    /**
109
     * Run a raw, unprepared query against the connection.
110
     *
111
     * @param  string  $query
112
     *
113
     * @return bool
114
     */
115
    public function unprepared($query): bool
116
    {
117
        return $this->run($query, [], function ($query) {
118
            if ($this->pretending()) {
119
                return true;
120
            }
121
122
            $statement = $$this->arangoClient->prepare($query);
123
            $statement->execute();
124
            $affectedDocumentCount = $statement->getWritesExecuted();
125
            $change = $affectedDocumentCount > 0;
126
127
            $this->recordsHaveBeenModified($change);
128
129
            return $change;
130
        });
131
    }
132
133
    /**
134
     * Returns the query execution plan. The query will not be executed.
135
     *
136
     * @param  string  $query
137
     * @param  array<mixed>  $bindings
138
     *
139
     * @return stdClass
140
     */
141 1
    public function explain(string|ArangoQueryBuilder $query, $bindings = []): stdClass
142
    {
143 1
        [$query, $bindings] = $this->handleQueryBuilder(
144
            $query,
145
            $bindings
146
        );
147
148 1
        $statement = $this->arangoClient->prepare($query, $bindings);
149
150 1
        return $statement->explain();
151
    }
152
153
    /**
154
     * @param  ArangoQueryBuilder|string  $query
155
     * @param  array  $bindings
156
     * @return array
157
     */
158 133
    protected function handleQueryBuilder($query, array $bindings): array
159
    {
160 133
        if ($query instanceof ArangoQueryBuilder) {
161 119
            $bindings = $query->binds;
162 119
            $query = $query->query;
163
        }
164 133
        return [$query, $bindings];
165
    }
166
167
    /**
168
     * Run a select statement against the database.
169
     *
170
     * @SuppressWarnings(PHPMD.BooleanArgumentFlag)
171
     *
172
     * @param string|ArangoQueryBuilder $query
173
     * @param array            $bindings
174
     * @param bool             $useReadPdo
175
     * @return mixed
176
     */
177 125
    public function select($query, $bindings = [], $useReadPdo = true)
178
    {
179 125
        return $this->execute($query, $bindings, $useReadPdo);
180
    }
181
182
    /**
183
     * Run an AQL query against the database and return the results.
184
     *
185
     * @SuppressWarnings(PHPMD.BooleanArgumentFlag)
186
     *
187
     * @param string|ArangoQueryBuilder $query
188
     * @param array<mixed>|null     $bindings
189
     * @param bool             $useReadPdo
190
     *
191
     * @return mixed
192
     */
193 131
    public function execute($query, ?array $bindings = [], $useReadPdo = true)
0 ignored issues
show
Unused Code introduced by
The parameter $useReadPdo is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

193
    public function execute($query, ?array $bindings = [], /** @scrutinizer ignore-unused */ $useReadPdo = true)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
194
    {
195
        // Usage of a separate DB to read date isn't supported at this time
196 131
        $useReadPdo = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $useReadPdo is dead and can be removed.
Loading history...
197
198 131
        [$query, $bindings] = $this->handleQueryBuilder(
199
            $query,
200
            $bindings
201
        );
202
203 131
        return $this->run($query, $bindings, function () use ($query, $bindings) {
204 131
            if ($this->pretending()) {
205
                return [];
206
            }
207
208 131
            $statement = $this->arangoClient->prepare($query, $bindings);
209 131
            $statement->execute();
210
211 126
            return $statement->fetchAll();
212
        });
213
    }
214
215
    /**
216
     * Get a new query builder instance.
217
     *
218
     * @return QueryBuilder
219
     */
220 120
    public function query(): QueryBuilder
221
    {
222 120
        return new QueryBuilder(
223
            $this,
224 120
            $this->getQueryGrammar(),
0 ignored issues
show
Bug introduced by
It seems like getQueryGrammar() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

224
            $this->/** @scrutinizer ignore-call */ 
225
                   getQueryGrammar(),
Loading history...
225 120
            $this->getPostProcessor()
0 ignored issues
show
Bug introduced by
It seems like getPostProcessor() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

225
            $this->/** @scrutinizer ignore-call */ 
226
                   getPostProcessor()
Loading history...
226
        );
227
    }
228
229
    /**
230
     * Run a SQL statement and log its execution context.
231
     *
232
     * @param  string  $query
233
     * @param  array  $bindings
234
     * @param  Closure  $callback
235
     * @return mixed
236
     *
237
     * @throws QueryException
238
     */
239 132
    protected function run($query, $bindings, Closure $callback)
240
    {
241 132
        foreach ($this->beforeExecutingCallbacks as $beforeExecutingCallback) {
242
            $beforeExecutingCallback($query, $bindings, $this);
243
        }
244
245 132
        $this->reconnectIfMissingConnection();
0 ignored issues
show
Bug introduced by
It seems like reconnectIfMissingConnection() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

245
        $this->/** @scrutinizer ignore-call */ 
246
               reconnectIfMissingConnection();
Loading history...
246
247 132
        $start = microtime(true);
248
249
        // Here we will run this query. If an exception occurs we'll determine if it was
250
        // caused by a connection that has been lost. If that is the cause, we'll try
251
        // to re-establish connection and re-run the query with a fresh connection.
252
        try {
253 132
            $result = $this->runQueryCallback($query, $bindings, $callback);
254 6
        } catch (QueryException $e) {
255 6
            $result = $this->handleQueryException(
0 ignored issues
show
Bug introduced by
It seems like handleQueryException() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

255
            /** @scrutinizer ignore-call */ 
256
            $result = $this->handleQueryException(
Loading history...
256
                $e,
257
                $query,
258
                $bindings,
259
                $callback
260
            );
261
        }
262
263
        // Once we have run the query we will calculate the time that it took to run and
264
        // then log the query, bindings, and execution time so we will report them on
265
        // the event that the developer needs them. We'll log time in milliseconds.
266 126
        $this->logQuery(
0 ignored issues
show
Bug introduced by
It seems like logQuery() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

266
        $this->/** @scrutinizer ignore-call */ 
267
               logQuery(
Loading history...
267
            $query,
268
            $bindings,
269 126
            $this->getElapsedTime($start)
0 ignored issues
show
Bug introduced by
It seems like getElapsedTime() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

269
            $this->/** @scrutinizer ignore-call */ 
270
                   getElapsedTime($start)
Loading history...
270
        );
271
272 126
        return $result;
273
    }
274
275
    /**
276
     * Run a SQL statement.
277
     *
278
     * @param  string  $query
279
     * @param  array  $bindings
280
     * @param  Closure  $callback
281
     * @return mixed
282
     *
283
     * @throws QueryException
284
     */
285 132
    protected function runQueryCallback($query, $bindings, Closure $callback)
286
    {
287
        // To execute the statement, we'll simply call the callback, which will actually
288
        // run the SQL against the PDO connection. Then we can calculate the time it
289
        // took to execute and log the query SQL, bindings and time in our memory.
290
        try {
291 132
            return $callback($query, $bindings);
292 6
        } catch (Exception $e) {
293
            // If an exception occurs when attempting to run a query, we'll format the error
294
            // message to include the bindings with SQL, which will make this exception a
295
            // lot more helpful to the developer instead of just the database's errors.
296
297 6
            throw new QueryException(
298
                $query,
299 6
                $this->prepareBindings($bindings),
0 ignored issues
show
Bug introduced by
It seems like prepareBindings() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

299
                $this->/** @scrutinizer ignore-call */ 
300
                       prepareBindings($bindings),
Loading history...
300
                $e
301
            );
302
        }
303
    }
304
}
305