1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace midorikocak\nanodb; |
6
|
|
|
|
7
|
|
|
use midorikocak\querymaker\QueryInterface; |
8
|
|
|
|
9
|
|
|
use function array_column; |
10
|
|
|
use function array_shift; |
11
|
|
|
use function ceil; |
12
|
|
|
use function preg_match; |
13
|
|
|
use function reset; |
14
|
|
|
|
15
|
|
|
class ResultSet |
16
|
|
|
{ |
17
|
|
|
private int $total; |
18
|
|
|
private int $pageSize; |
19
|
|
|
private int $page; |
20
|
|
|
private ?int $offset; |
21
|
|
|
private ?int $limit; |
22
|
|
|
private ?string $orderBy; |
23
|
|
|
private ?string $order; |
24
|
|
|
private string $tableName; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @return static |
28
|
|
|
*/ |
29
|
1 |
|
public static function getResultSet( |
30
|
|
|
Database $db, |
31
|
|
|
QueryInterface $query |
32
|
|
|
): self { |
33
|
1 |
|
$counterQuery = $query->count(null, true); |
34
|
1 |
|
$db->query($counterQuery); |
35
|
1 |
|
$db->execute(); |
36
|
|
|
|
37
|
1 |
|
$counted = array_column($db->fetchAll(), 'COUNT(*)'); |
38
|
|
|
|
39
|
1 |
|
$resultSet = new self(); |
40
|
1 |
|
$resultSet->total = (int) reset($counted); |
41
|
|
|
|
42
|
1 |
|
$queryString = $query->getQuery(); |
43
|
1 |
|
preg_match('/FROM (\S*)( WHERE)?/', $queryString, $tableMatch); |
44
|
|
|
|
45
|
1 |
|
preg_match('/OFFSET (\d+)/', $queryString, $offsetMatch); |
46
|
1 |
|
preg_match('/LIMIT (\d+)/', $queryString, $limitMatch); |
47
|
1 |
|
preg_match('/ORDER BY (\S+)( ASC| DESC)/', $queryString, $orderMatch); |
48
|
|
|
|
49
|
1 |
|
array_shift($offsetMatch); |
50
|
1 |
|
array_shift($limitMatch); |
51
|
1 |
|
array_shift($orderMatch); |
52
|
|
|
|
53
|
1 |
|
$resultSet->limit = (int) (reset($limitMatch) ?? 0); |
54
|
1 |
|
$resultSet->offset = (int) (reset($offsetMatch) ?? 0); |
55
|
1 |
|
$resultSet->orderBy = reset($orderMatch) !== false ? reset($orderMatch) : null; |
56
|
1 |
|
$resultSet->order = $orderMatch[1] ?? null; |
57
|
1 |
|
$resultSet->tableName = $tableMatch[1] ?? ''; |
58
|
|
|
|
59
|
1 |
|
$resultSet->pageSize = $resultSet->limit ?? $resultSet->total; |
60
|
|
|
|
61
|
1 |
|
$resultSet->page = (int) ceil($resultSet->offset / $resultSet->pageSize); |
62
|
1 |
|
return $resultSet; |
63
|
|
|
} |
64
|
|
|
|
65
|
1 |
|
public static function getResultArray(Database $db, QueryInterface $query): array |
66
|
|
|
{ |
67
|
1 |
|
return self::getResultSet($db, $query)->toArray(); |
68
|
|
|
} |
69
|
|
|
|
70
|
1 |
|
public function toArray(): array |
71
|
|
|
{ |
72
|
|
|
return [ |
73
|
1 |
|
'total' => $this->total, |
74
|
1 |
|
'pageSize' => $this->pageSize, |
75
|
1 |
|
'page' => $this->page, |
76
|
1 |
|
'offset' => $this->offset, |
77
|
1 |
|
'limit' => $this->limit, |
78
|
1 |
|
'orderBy' => $this->orderBy, |
79
|
1 |
|
'tableName' => $this->tableName, |
80
|
|
|
]; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|