| 1 |
<?php |
| 2 |
|
| 3 |
namespace QuadLayers\WP_Orm\Builder; |
| 4 |
|
| 5 |
use QuadLayers\WP_Orm\Factory\CollectionFactory; |
| 6 |
use QuadLayers\WP_Orm\Mapper\CollectionMapper; |
| 7 |
use QuadLayers\WP_Orm\Repository\CollectionRepository; |
| 8 |
|
| 9 |
class CollectionRepositoryBuilder |
| 10 |
{ |
| 11 |
/** |
| 12 |
* @var string |
| 13 |
*/ |
| 14 |
private $table; |
| 15 |
|
| 16 |
/** |
| 17 |
* @var string |
| 18 |
*/ |
| 19 |
private $primaryKey; |
| 20 |
|
| 21 |
/** |
| 22 |
* @var string |
| 23 |
*/ |
| 24 |
private $entityClass; |
| 25 |
|
| 26 |
/** |
| 27 |
* @var array|null |
| 28 |
*/ |
| 29 |
private $defaultEntities; |
| 30 |
|
| 31 |
/** |
| 32 |
* @var bool|null |
| 33 |
*/ |
| 34 |
private $autoIncrement = null; |
| 35 |
|
| 36 |
public function setTable(string $table): self |
| 37 |
{ |
| 38 |
$this->table = $table; |
| 39 |
return $this; |
| 40 |
} |
| 41 |
|
| 42 |
public function setEntity(string $entityClass): self |
| 43 |
{ |
| 44 |
if (!class_exists($entityClass)) { |
| 45 |
throw new \InvalidArgumentException("Class '{$entityClass}' does not exist."); |
| 46 |
} |
| 47 |
|
| 48 |
$this->entityClass = $entityClass; |
| 49 |
return $this; |
| 50 |
} |
| 51 |
|
| 52 |
public function setDefaultEntities(array $defaultEntities): self |
| 53 |
{ |
| 54 |
$this->defaultEntities = $defaultEntities; |
| 55 |
return $this; |
| 56 |
} |
| 57 |
|
| 58 |
public function setAutoIncrement(bool $autoIncrement): self |
| 59 |
{ |
| 60 |
$this->autoIncrement = $autoIncrement; |
| 61 |
return $this; |
| 62 |
} |
| 63 |
|
| 64 |
public function setPrimaryKey(): self |
| 65 |
{ |
| 66 |
|
| 67 |
// Check if the entity class has the primaryKey property |
| 68 |
if (!property_exists($this->entityClass, 'primaryKey') || !isset($this->entityClass::$primaryKey)) { |
| 69 |
throw new \InvalidArgumentException("Class '{$this->entityClass}' does not have the property 'primaryKey'."); |
| 70 |
} |
| 71 |
|
| 72 |
$primaryKey = $this->entityClass::$primaryKey; |
| 73 |
|
| 74 |
// Check if the entity class has the primaryKey property |
| 75 |
if (!property_exists($this->entityClass, $primaryKey)) { |
| 76 |
throw new \InvalidArgumentException("Class '{$this->entityClass}' does not have the property '{$primaryKey}'."); |
| 77 |
} |
| 78 |
|
| 79 |
$this->primaryKey = $primaryKey; |
| 80 |
|
| 81 |
return $this; |
| 82 |
} |
| 83 |
|
| 84 |
public function getRepository(): CollectionRepository |
| 85 |
{ |
| 86 |
|
| 87 |
if (null === $this->autoIncrement) { |
| 88 |
throw new \InvalidArgumentException("Auto increment is not set."); |
| 89 |
} |
| 90 |
|
| 91 |
$this->setPrimaryKey(); |
| 92 |
$factory = new CollectionFactory($this->entityClass); |
| 93 |
$mapper = new CollectionMapper($factory); |
| 94 |
return new CollectionRepository($mapper, $this->table, $this->primaryKey, $this->autoIncrement, $this->defaultEntities); |
| 95 |
} |
| 96 |
} |
| 97 |
|