summaryrefslogtreecommitdiff
path: root/src/DB.php
blob: f91e934c478373dbb4f59e46871dfced7a8824a9 (plain)
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
<?php

namespace App;

class DB {
  public static \PDO $connection;

  public static function init(): void
  {
    $driver = $_ENV['DB_DRIVER'] ?? 'pgsql';
    $host = $_ENV['DB_HOST'] ?? 'db';
    $port = $_ENV['DB_PORT'] ?? 5432;
    $dbname = $_ENV['DB_NAME'];
    $user = $_ENV['DB_USER'];
    $password = $_ENV['DB_PASSWORD'];

    self::$connection = new \PDO("pgsql:host=$host;port=$port;dbname=$dbname", $user, $password);
  }

  /**
   * @param string $query
   * @param array $params
   */
  public static function query(string $query, array $params = []): \PDOStatement|false
  {
    /**@var \PDOStatement $statement*/
    $statement = self::$connection->prepare($query);
    $statement->execute($params);

    return $statement;
  }

  /**
   * @param string $class
   * @param string $query
   * @param array $params
   *
   * @return array<object>
   */
  public static function fetch(string $class, string $query, array $params = []): array
  {
    $rows = DB::query($query, $params)->fetchAll(\PDO::FETCH_ASSOC);

    $results = [];
    foreach ($rows as $row) {
      $results[] = DB::convertToModel($class, $row);
    }

    return $results;
  }

  /**
   * @param string $class
   * @param array $row
   *
   * @return object
   */
  public static function convertToModel(string $class, array $row): object
  {
    $object = new $class();

    foreach ($row as $columnKey => $columnValue) {
      $objectKey = explode('_', $columnKey);
      $objectKey = $objectKey[0] . implode('', array_map('ucwords', array_slice($objectKey, 1)));

      if (property_exists($object, $objectKey)) {
        $propertyType = (new \ReflectionProperty($object, $objectKey))->getType();

        if (class_exists($propertyType->getName())) {
          $object->$objectKey = new ($propertyType->getName())($columnValue);
        } else {
          $object->$objectKey = $columnValue;
        }
      }
    }

    return $object;
  }
}