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

namespace Elements;

use Doctrine\ORM\Cache;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\Driver\AttributeDriver;
use Doctrine\ORM\Tools\Setup;

class DB
{
  public static EntityManager $entityManager;

  /**
   * DB constructor.
   */
  public static function init()
  {
    $isDevMode = true;
    $proxyDir = null;
    $cache = null;
    $config = Setup::createConfiguration($isDevMode, $proxyDir, $cache);
    $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver([__DIR__ . '/Model'], true));
    #$config->setMetadataDriverImpl(new AttributeDriver([__DIR__ . '/Model']));

    $conn = array(
      'driver' => 'pdo_sqlite',
      'path' => dirname(__DIR__) . '/db.sqlite',
    );

    self::$entityManager = EntityManager::create($conn, $config);
  }

  /**
   * @param object $entity
   * @param array $criteria
   */
  public static function save(object $entity, array $criteria = [])
  {
    $repository = self::$entityManager->getRepository(get_class($entity));
    $exists = $repository->findOneBy($criteria);

    if (! empty($criteria) && ! is_null($exists)) {
      foreach (get_object_vars($entity) as $key => $value) {
	$exists->$key = $value;
      }
    } else {
      $exists = $entity;
    }

    self::$entityManager->persist($exists);
    self::$entityManager->flush();
  }
}