-
Notifications
You must be signed in to change notification settings - Fork 0
/
DbalDataProvider.php
98 lines (79 loc) · 2.25 KB
/
DbalDataProvider.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
namespace Kora\DataProvider\Doctrine\Dbal;
use Doctrine\DBAL\Query\QueryBuilder;
use Kora\DataProvider\AbstractDataProvider;
use Kora\DataProvider\Mapper;
use Kora\DataProvider\OperatorImplementationsList;
/**
* Class DbalDataProvider
* @author Paweł Gierlasiński <[email protected]>
*/
class DbalDataProvider extends AbstractDataProvider
{
/**
* @var QueryBuilder
*/
private $queryBuilder;
/**
* DbalDataProvider constructor.
* @param QueryBuilder $queryBuilder
* @param OperatorImplementationsList $implementationsList
* @param Mapper $mapper
*/
public function __construct(QueryBuilder $queryBuilder, OperatorImplementationsList $implementationsList, Mapper $mapper)
{
parent::__construct($implementationsList, $mapper);
$this->queryBuilder = $queryBuilder;
}
/**
* @param string $name
* @return string
*/
public function getFieldMapping(string $name): string
{
$map = $this->mapper->getOperatorFieldMap();
if (isset($map[$name])) return $map[$name];
$from = $this->queryBuilder->getQueryPart('from') ?? [];
$mainAlias = $from[0]['alias'] ?? [];
if (empty($mainAlias)) return $name;
return $mainAlias . '.' . $name;
}
/**
* @return array
*/
public function fetchFromDataSource(): array
{
$stmt = $this->queryBuilder->execute();
return $stmt->fetchAll();
}
/**
* Little dirty, maybe there's better way. It should also handle GROUP BY scenario
* @return int
*/
public function count(): int
{
$limit = $this->queryBuilder->getMaxResults();
$offset = $this->queryBuilder->getFirstResult();
$this->queryBuilder->setMaxResults(null);
$this->queryBuilder->setFirstResult(null);
$sql = $this->queryBuilder->getSQL();
$this->queryBuilder->setMaxResults($limit);
$this->queryBuilder->setFirstResult($offset);
$stmt = $this->queryBuilder->getConnection()->prepare("
SELECT COUNT(*)
FROM ($sql) AS counter
");
foreach ($this->queryBuilder->getParameters() as $name => $value) {
$stmt->bindValue($name, $value, $this->queryBuilder->getParameterType($name));
}
$stmt->execute();
return $stmt->fetchColumn();
}
/**
* @return QueryBuilder
*/
public function getQueryBuilder(): QueryBuilder
{
return $this->queryBuilder;
}
}