szurubooru/src/Dao/AbstractDao.php

94 lines
2.1 KiB
PHP
Raw Normal View History

<?php
namespace Szurubooru\Dao;
abstract class AbstractDao implements ICrudDao
{
2014-09-14 16:16:15 +02:00
protected $pdo;
protected $fpdo;
protected $tableName;
protected $entityName;
2014-08-30 17:10:45 +02:00
protected $entityConverter;
2014-08-30 17:10:45 +02:00
public function __construct(
\Szurubooru\DatabaseConnection $databaseConnection,
2014-09-14 16:16:15 +02:00
$tableName,
2014-08-30 17:10:45 +02:00
$entityName)
{
2014-08-30 17:10:45 +02:00
$this->entityConverter = new EntityConverter($entityName);
$this->entityName = $entityName;
2014-09-14 16:16:15 +02:00
$this->tableName = $tableName;
$this->pdo = $databaseConnection->getPDO();
$this->fpdo = new \FluentPDO($this->pdo);
}
2014-09-14 16:16:15 +02:00
public function getTableName()
{
2014-09-14 16:16:15 +02:00
return $this->tableName;
}
public function getEntityConverter()
{
return $this->entityConverter;
}
public function save(&$entity)
{
2014-08-30 17:10:45 +02:00
$arrayEntity = $this->entityConverter->toArray($entity);
if ($entity->getId())
{
2014-09-14 16:16:15 +02:00
$this->fpdo->update($this->tableName)->set($arrayEntity)->where('id', $entity->getId())->execute();
}
else
{
2014-09-14 16:16:15 +02:00
$this->fpdo->insertInto($this->tableName)->values($arrayEntity)->execute();
$arrayEntity['id'] = $this->pdo->lastInsertId();
}
2014-08-30 17:10:45 +02:00
$entity = $this->entityConverter->toEntity($arrayEntity);
return $entity;
}
public function findAll()
{
$entities = [];
2014-09-14 16:16:15 +02:00
$query = $this->fpdo->from($this->tableName);
foreach ($query as $arrayEntity)
{
2014-08-30 17:10:45 +02:00
$entity = $this->entityConverter->toEntity($arrayEntity);
2014-09-14 16:16:15 +02:00
$entities[$entity->getId()] = $entity;
}
return $entities;
}
public function findById($entityId)
{
2014-09-14 16:16:15 +02:00
return $this->findOneBy('id', $entityId);
}
public function deleteAll()
{
2014-09-14 16:16:15 +02:00
$this->fpdo->deleteFrom($this->tableName)->execute();
}
public function deleteById($entityId)
{
2014-09-14 16:16:15 +02:00
return $this->deleteBy('id', $entityId);
}
protected function hasAnyRecords()
{
return count(iterator_to_array($this->fpdo->from($this->tableName)->limit(1))) > 0;
}
protected function findOneBy($columnName, $value)
{
$arrayEntity = iterator_to_array($this->fpdo->from($this->tableName)->where($columnName, $value));
return $arrayEntity ? $this->entityConverter->toEntity($arrayEntity[0]) : null;
}
protected function deleteBy($columnName, $value)
{
$this->fpdo->deleteFrom($this->tableName)->where($columnName, $value)->execute();
}
}