Skip to content

Instantly share code, notes, and snippets.

@GDXbsv
Created November 30, 2021 10:34
Show Gist options
  • Select an option

  • Save GDXbsv/218fefc8412ac2493d6b2483e43ee3aa to your computer and use it in GitHub Desktop.

Select an option

Save GDXbsv/218fefc8412ac2493d6b2483e43ee3aa to your computer and use it in GitHub Desktop.
Table Gateway DBAL PHP
<?php
declare(strict_types=1);
namespace App\Notification;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\Type;
use JetBrains\PhpStorm\Immutable;
/**
* @template T as object
*/
class Gateway
{
/**
* @var non-empty-string
*/
protected string $query;
/**
* @var class-string<T>
*/
protected string $mapTo;
public function __construct(private Connection $connection)
{
}
/**
* @param non-empty-string $query
*/
public function query(string $query): self
{
$this->query = $query;
return $this;
}
/**
* @param class-string<T> $className
*/
public function mapTo(string $className): self
{
$this->mapTo = $className;
return $this;
}
/**
* @return T
*/
public function one(): object {
$stmt = $this->connection->prepare($this->query);
$stmt->getWrappedStatement();
$resultSetMapping = ResultSetMapping::forStatement($statement);
$row = $this->makeRequest();
}
/**
* @return list<T>
*/
public function many(): array {
}
protected function makeRequest(): array {
}
}
/**
* @internal
* @immutable
* @psalm-immutable
*/
#[Immutable]
final class ResultSetMapping
{
/**
* @var array<non-empty-string, non-empty-string>
*/
private static array $typeMapping = [
'timestamptz' => 'datetimetz_immutable',
'timestamp' => 'datetime_immutable',
'json' => 'json',
'jsonb' => 'json',
];
/**
* @var Type[]
*/
private array $mappings;
/**
* @param Type[] $mappings
*/
private function __construct(array $mappings)
{
$this->mappings = $mappings;
}
public static function forStatement(\PDOStatement $statement): self
{
$resultSetMapping = [];
for ($i = 0; $i < $statement->columnCount(); ++$i) {
$meta = $statement->getColumnMeta($i);
if (isset($meta['native_type'], self::$typeMapping[$meta['native_type']])) {
$resultSetMapping[$meta['name']] = Type::getType(self::$typeMapping[$meta['native_type']]);
}
}
return new self($resultSetMapping);
}
public function mapColumn(AbstractPlatform $platform, string $columnName, $value)
{
if (!isset($this->mappings[$columnName])) {
return $value;
}
return $this->mappings[$columnName]->convertToPHPValue($value, $platform);
}
public function mapKnownColumns(AbstractPlatform $platform, array $row): array
{
foreach ($this->mappings as $field => $type) {
if (array_key_exists($field, $row)) {
$row[$field] = $type->convertToPHPValue($row[$field], $platform);
}
}
return $row;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment