diff options
author | Daniel Weipert <code@drogueronin.de> | 2022-01-10 20:29:04 +0100 |
---|---|---|
committer | Daniel Weipert <code@drogueronin.de> | 2022-01-10 20:29:04 +0100 |
commit | a319f3a419790925bed539ba141038c72a83e70f (patch) | |
tree | dfb24183cc693863df733e190dbbc6da93bb82e5 /src/DB.php |
Initial commit
Diffstat (limited to 'src/DB.php')
-rw-r--r-- | src/DB.php | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/src/DB.php b/src/DB.php new file mode 100644 index 0000000..c04d189 --- /dev/null +++ b/src/DB.php @@ -0,0 +1,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(); + } +} + |