| 1 |
<?php |
| 2 |
|
| 3 |
namespace QuadLayers\WP_Orm\Factory; |
| 4 |
|
| 5 |
use QuadLayers\WP_Orm\Entity\EntityInterface; |
| 6 |
|
| 7 |
use function QuadLayers\WP_Orm\V2\Helpers\getObjectSchema; |
| 8 |
use function QuadLayers\WP_Orm\V2\Helpers\getSanitizedData; |
| 9 |
|
| 10 |
abstract class AbstractFactory |
| 11 |
{ |
| 12 |
/** |
| 13 |
* @var string |
| 14 |
*/ |
| 15 |
private $entityClass; |
| 16 |
|
| 17 |
public function __construct(string $entityClass) |
| 18 |
{ |
| 19 |
$this->entityClass = $entityClass; |
| 20 |
} |
| 21 |
|
| 22 |
public function create(array $data): EntityInterface |
| 23 |
{ |
| 24 |
// Create a new instance of the entity |
| 25 |
$entity = new $this->entityClass(); |
| 26 |
|
| 27 |
// Get the default values of the entity, new static() is used to get the defaults of the child class |
| 28 |
$entityDefaults = $entity->getDefaults(); |
| 29 |
|
| 30 |
$entitySchema = getObjectSchema($entityDefaults); |
| 31 |
|
| 32 |
$sanitizedData = getSanitizedData($data, $entitySchema); |
| 33 |
|
| 34 |
// Loop through each data item |
| 35 |
foreach ($sanitizedData as $propertyName => $value) { |
| 36 |
// Set the value of the property |
| 37 |
$entity->set($propertyName, $value); |
| 38 |
} |
| 39 |
|
| 40 |
// Get private properties of the entity |
| 41 |
$entityPrivates = $entity::PRIVATE_PROPERTIES; |
| 42 |
|
| 43 |
// Check if the entity has private properties and update them |
| 44 |
if (count($entityPrivates) > 0) { |
| 45 |
// Loop through each private property |
| 46 |
foreach ($entityPrivates as $propertyName) { |
| 47 |
if (array_key_exists($propertyName, $data)) { |
| 48 |
// Set the value of the property |
| 49 |
$entity->set($propertyName, $data[$propertyName]); |
| 50 |
} |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
return $entity; |
| 55 |
} |
| 56 |
} |
| 57 |
|