InlineParameterFormatter.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. declare(strict_types=1);
  3. namespace Doctrine\Migrations;
  4. use Doctrine\DBAL\Connection;
  5. use Doctrine\DBAL\Types\Type;
  6. use function array_map;
  7. use function implode;
  8. use function is_array;
  9. use function is_bool;
  10. use function is_int;
  11. use function is_string;
  12. use function sprintf;
  13. /**
  14. * The InlineParameterFormatter class is responsible for formatting SQL query parameters to a string
  15. * for display output.
  16. *
  17. * @internal
  18. */
  19. final class InlineParameterFormatter implements ParameterFormatter
  20. {
  21. /** @var Connection */
  22. private $connection;
  23. public function __construct(Connection $connection)
  24. {
  25. $this->connection = $connection;
  26. }
  27. /**
  28. * @param mixed[] $params
  29. * @param mixed[] $types
  30. */
  31. public function formatParameters(array $params, array $types): string
  32. {
  33. if ($params === []) {
  34. return '';
  35. }
  36. $formattedParameters = [];
  37. foreach ($params as $key => $value) {
  38. $type = $types[$key] ?? 'string';
  39. $formattedParameter = '[' . $this->formatParameter($value, $type) . ']';
  40. $formattedParameters[] = is_string($key)
  41. ? sprintf(':%s => %s', $key, $formattedParameter)
  42. : $formattedParameter;
  43. }
  44. return sprintf('with parameters (%s)', implode(', ', $formattedParameters));
  45. }
  46. /**
  47. * @param string|int $value
  48. * @param string|int $type
  49. *
  50. * @return string|int
  51. */
  52. private function formatParameter($value, $type)
  53. {
  54. if (is_string($type) && Type::hasType($type)) {
  55. return Type::getType($type)->convertToDatabaseValue(
  56. $value,
  57. $this->connection->getDatabasePlatform()
  58. );
  59. }
  60. return $this->parameterToString($value);
  61. }
  62. /**
  63. * @param int[]|bool[]|string[]|array|int|string|bool $value
  64. */
  65. private function parameterToString($value): string
  66. {
  67. if (is_array($value)) {
  68. return implode(', ', array_map(function ($value): string {
  69. return $this->parameterToString($value);
  70. }, $value));
  71. }
  72. if (is_int($value) || is_string($value)) {
  73. return (string) $value;
  74. }
  75. if (is_bool($value)) {
  76. return $value === true ? 'true' : 'false';
  77. }
  78. }
  79. }