Files
contabilidad/api/common/Alias/Repository.php

63 lines
1.9 KiB
PHP
Raw Normal View History

2022-08-05 21:28:59 -04:00
<?php
namespace Common\Alias;
use Common\Concept\Database;
use Common\Concept\Model;
use Common\Concept\Repository as RepositoryInterface;
abstract class Repository implements RepositoryInterface
{
protected string $table;
public function setTable(string $table): RepositoryInterface
{
$this->table = $table;
return $this;
}
public function getTable(): string
{
return $this->table;
}
protected array $properties;
public function addProperty(string $name): RepositoryInterface
{
$this->properties []= $name;
return $this;
}
public function setProperties(array $properties): RepositoryInterface
{
foreach ($properties as $property) {
$this->addProperty($property);
}
return $this;
}
public function getProperties(): array
{
return $this->properties;
}
protected Database $database;
public function setDatabase(Database $database): RepositoryInterface
{
$this->database = $database;
return $this;
}
public function getDatabase(): Database
{
return $this->database;
}
public function fetchAll(): array
{
$query = "SELECT * FROM {$this->getTable()}";
return array_map([$this, 'load'], $this->getDatabase()->query($query));
}
public function save(Model $model): void
{
$columns = implode(', ', array_map(function($item) {return "'{$item}'";}, $this->getProperties()));
$values = implode(', ', array_map(function($item) {return '?';}, $this->getProperties()));
$query = "INSERT INTO {$this->getTable()} ({$columns}) VALUES ({$values})";
$values = array_map(function($item) use ($model) {$method = str_replace(' ', '', ucwords(str_replace('_', '', $item)));return $model->{"get{$method}"}();}, $this->getProperties());
$this->getDatabase()->prepare($query)->insert($values);
}
}