| 1 |
<?php |
| 2 |
|
| 3 |
namespace QuadLayers\WP_Orm\Entity; |
| 4 |
|
| 5 |
use function QuadLayers\WP_Orm\V2\Helpers\arrayRecursiveDiff; |
| 6 |
use function QuadLayers\WP_Orm\V2\Helpers\getSanitizeValue; |
| 7 |
use function QuadLayers\WP_Orm\V2\Helpers\isValidValue; |
| 8 |
|
| 9 |
abstract class CollectionEntity extends SingleEntity |
| 10 |
{ |
| 11 |
const PRIVATE_PROPERTIES = ['primaryKey','allowDelete', 'allowUpdate', 'sanitizeProperties', 'validateProperties']; |
| 12 |
|
| 13 |
/** |
| 14 |
* @var string |
| 15 |
*/ |
| 16 |
public static $primaryKey; |
| 17 |
/** |
| 18 |
* @var bool |
| 19 |
*/ |
| 20 |
private $allowDelete = true; |
| 21 |
/** |
| 22 |
* @var bool |
| 23 |
*/ |
| 24 |
private $allowUpdate = true; |
| 25 |
|
| 26 |
public function get(string $propertyName) |
| 27 |
{ |
| 28 |
if (property_exists($this, $propertyName)) { |
| 29 |
return $this->$propertyName; |
| 30 |
} |
| 31 |
} |
| 32 |
|
| 33 |
public function set(string $propertyName, $value): void |
| 34 |
{ |
| 35 |
if (!property_exists($this, $propertyName)) { |
| 36 |
throw new \InvalidArgumentException("Property '{$propertyName}' does not exist."); |
| 37 |
} |
| 38 |
|
| 39 |
$sanitizedValue = getSanitizeValue($this, $propertyName, $value); |
| 40 |
|
| 41 |
$isValid = isValidValue($this, $propertyName, $sanitizedValue); |
| 42 |
|
| 43 |
if (!$isValid) { |
| 44 |
throw new \Exception(sprintf('Value "%s" is not a valid value for the "%s" property.', $value, $propertyName), 400); |
| 45 |
} |
| 46 |
|
| 47 |
$this->$propertyName = $sanitizedValue; |
| 48 |
} |
| 49 |
|
| 50 |
public function getModifiedProperties(): array |
| 51 |
{ |
| 52 |
// Get the current state of the object |
| 53 |
|
| 54 |
$defaults = $this->getDefaults(); |
| 55 |
/** |
| 56 |
* Remove the primary key from the defaults array |
| 57 |
* Always assume that the primary key is modified |
| 58 |
*/ |
| 59 |
if (array_key_exists(static::$primaryKey, $defaults)) { |
| 60 |
unset($defaults[static::$primaryKey]); |
| 61 |
} |
| 62 |
$properties = $this->getProperties(); |
| 63 |
|
| 64 |
// Compare the current state with the initial state and get the modified properties |
| 65 |
$modifiedProperties = arrayRecursiveDiff($defaults, $properties); |
| 66 |
|
| 67 |
// Return the modified properties |
| 68 |
return $modifiedProperties; |
| 69 |
} |
| 70 |
} |
| 71 |
|