-
Notifications
You must be signed in to change notification settings - Fork 0
/
ParametrizedMigrationQuery.php
110 lines (100 loc) · 3.22 KB
/
ParametrizedMigrationQuery.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
99
100
101
102
103
104
105
106
107
108
109
110
<?php
namespace Effiana\MigrationBundle\Migration;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Types\Type;
use Psr\Log\LoggerInterface;
abstract class ParametrizedMigrationQuery implements MigrationQuery, ConnectionAwareInterface
{
/**
* @var Connection
*/
protected $connection;
/**
* {@inheritdoc}
*/
public function setConnection(Connection $connection)
{
$this->connection = $connection;
}
/**
* Adds a query to a log
*
* @param LoggerInterface $logger
* @param string $query
* @param array $params
* @param array $types
*/
protected function logQuery(LoggerInterface $logger, $query, array $params = [], array $types = [])
{
$logger->info($query);
if (!empty($params)) {
$resolvedParams = $this->resolveParams($params, $types);
$logger->info('Parameters:');
foreach ($resolvedParams as $key => $val) {
if (is_array($val)) {
$val = implode(',', $val);
}
$logger->info(sprintf('[%s] = %s', $key, $val));
}
}
}
/**
* Resolves the parameters to a format which can be displayed.
*
* @param array $params
* @param array $types
*
* @return array
*/
protected function resolveParams(array $params, array $types)
{
$resolvedParams = array();
// Check whether parameters are positional or named. Mixing is not allowed.
if (is_int(key($params))) {
// Positional parameters
$typeOffset = array_key_exists(0, $types) ? -1 : 0;
$bindIndex = 1;
foreach ($params as $value) {
$typeIndex = $bindIndex + $typeOffset;
if (isset($types[$typeIndex])) {
$type = $types[$typeIndex];
$value = $this->convertToDatabaseValue($value, $type);
$resolvedParams[$bindIndex] = $value;
} else {
$resolvedParams[$bindIndex] = $value;
}
$bindIndex++;
}
} else {
// Named parameters
foreach ($params as $name => $value) {
if (isset($types[$name])) {
$type = $types[$name];
$value = $this->convertToDatabaseValue($value, $type);
$resolvedParams[$name] = $value;
} else {
$resolvedParams[$name] = $value;
}
}
}
return $resolvedParams;
}
/**
* Converts a value from its PHP representation to its database representation.
*
* @param mixed $value
* @param string|Type $type
*
* @return array the (escaped) value
*/
protected function convertToDatabaseValue($value, $type)
{
if (is_string($type)) {
$type = Type::getType($type);
}
if ($type instanceof Type) {
$value = $type->convertToDatabaseValue($value, $this->connection->getDatabasePlatform());
}
return $value;
}
}