| 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 SingleVirtualRepository implements SingleVirtualRepositoryInterface |
| 9 |
{ |
| 10 |
/** |
| 11 |
* @var SingleMapperInterface |
| 12 |
*/ |
| 13 |
private $mapper; |
| 14 |
|
| 15 |
/** |
| 16 |
* @var EntityInterface|null |
| 17 |
*/ |
| 18 |
private $cache = null; |
| 19 |
|
| 20 |
public function __construct(SingleMapperInterface $mapper) |
| 21 |
{ |
| 22 |
$this->mapper = $mapper; |
| 23 |
} |
| 24 |
|
| 25 |
public function save(EntityInterface $entity): EntityInterface |
| 26 |
{ |
| 27 |
return $this->cache = $entity; |
| 28 |
} |
| 29 |
|
| 30 |
public function update(array $data): EntityInterface |
| 31 |
{ |
| 32 |
$entity = $this->cache; |
| 33 |
|
| 34 |
if ($entity === null) { |
| 35 |
return false; // Or throw an exception, as you prefer |
| 36 |
} |
| 37 |
// Merge old and new data |
| 38 |
$updatedData = array_merge($entity->getProperties(), $data); |
| 39 |
$updatedEntity = $this->mapper->toEntity($updatedData); |
| 40 |
return $this->save($updatedEntity); |
| 41 |
} |
| 42 |
|
| 43 |
public function delete(): bool |
| 44 |
{ |
| 45 |
$this->cache = null; |
| 46 |
return true; |
| 47 |
} |
| 48 |
|
| 49 |
public function create(array $data): EntityInterface |
| 50 |
{ |
| 51 |
$entity = $this->mapper->toEntity($data); |
| 52 |
return $this->save($entity); |
| 53 |
} |
| 54 |
} |
| 55 |
|