| 1 |
<?php |
| 2 |
|
| 3 |
namespace QuadLayers\WP_Orm\Repository; |
| 4 |
|
| 5 |
use QuadLayers\WP_Orm\Entity\EntityInterface; |
| 6 |
use QuadLayers\WP_Orm\Mapper\SingleMapperInterface; |
| 7 |
|
| 8 |
class SingleRepository implements SingleRepositoryInterface |
| 9 |
{ |
| 10 |
/** |
| 11 |
* @var SingleMapperInterface |
| 12 |
*/ |
| 13 |
private $mapper; |
| 14 |
|
| 15 |
/** |
| 16 |
* @var string |
| 17 |
*/ |
| 18 |
private $table; |
| 19 |
|
| 20 |
/** |
| 21 |
* @var EntityInterface|null |
| 22 |
*/ |
| 23 |
private $cache = null; |
| 24 |
|
| 25 |
public function __construct(SingleMapperInterface $mapper, string $table) |
| 26 |
{ |
| 27 |
$this->mapper = $mapper; |
| 28 |
$this->table = $table; |
| 29 |
} |
| 30 |
|
| 31 |
public function find(): ?EntityInterface |
| 32 |
{ |
| 33 |
if ($this->cache !== null) { |
| 34 |
return $this->cache; |
| 35 |
} |
| 36 |
|
| 37 |
$data = get_option($this->table, null); |
| 38 |
$this->cache = $data ? $this->mapper->toEntity($data) : null; |
| 39 |
return $this->cache; |
| 40 |
} |
| 41 |
|
| 42 |
public function save(EntityInterface $entity): bool |
| 43 |
{ |
| 44 |
$this->cache = $entity; |
| 45 |
$data = $this->mapper->toArray($entity); |
| 46 |
return update_option($this->table, $data); |
| 47 |
} |
| 48 |
|
| 49 |
public function update(array $data): bool |
| 50 |
{ |
| 51 |
$entity = $this->find(); |
| 52 |
if ($entity === null) { |
| 53 |
return false; // or throw an exception, as you prefer |
| 54 |
} |
| 55 |
// merge old and new data |
| 56 |
$updatedData = array_merge($entity->getProperties(), $data); |
| 57 |
$updatedEntity = $this->mapper->toEntity($updatedData); |
| 58 |
return $this->save($updatedEntity); |
| 59 |
} |
| 60 |
|
| 61 |
public function delete(): bool |
| 62 |
{ |
| 63 |
$this->cache = null; |
| 64 |
return delete_option($this->table); |
| 65 |
} |
| 66 |
|
| 67 |
public function create(array $data): bool |
| 68 |
{ |
| 69 |
$entity = $this->mapper->toEntity($data); |
| 70 |
return $this->save($entity); |
| 71 |
} |
| 72 |
|
| 73 |
public function getTable(): string |
| 74 |
{ |
| 75 |
return $this->table; |
| 76 |
} |
| 77 |
} |
| 78 |
|