| 1 |
<?php |
| 2 |
/** |
| 3 |
* Base model class for all Parse.ly models |
| 4 |
* |
| 5 |
* @package Parsely |
| 6 |
* @since 3.16.0 |
| 7 |
*/ |
| 8 |
|
| 9 |
declare(strict_types=1); |
| 10 |
|
| 11 |
namespace Parsely\Models; |
| 12 |
|
| 13 |
/** |
| 14 |
* Base model class for all Parse.ly models. |
| 15 |
* |
| 16 |
* @since 3.16.0 |
| 17 |
*/ |
| 18 |
abstract class Base_Model { |
| 19 |
/** |
| 20 |
* The unique ID of the model. |
| 21 |
* |
| 22 |
* @since 3.16.0 |
| 23 |
* @var string The unique ID of the model. |
| 24 |
*/ |
| 25 |
public $uid; |
| 26 |
|
| 27 |
/** |
| 28 |
* Base model constructor. |
| 29 |
* |
| 30 |
* @since 3.16.0 |
| 31 |
*/ |
| 32 |
public function __construct() { |
| 33 |
$this->uid = $this->generate_uid(); |
| 34 |
} |
| 35 |
|
| 36 |
/** |
| 37 |
* Returns the unique ID of the model. |
| 38 |
* |
| 39 |
* @since 3.16.0 |
| 40 |
* |
| 41 |
* @return string The unique ID of the model. |
| 42 |
*/ |
| 43 |
public function get_uid(): string { |
| 44 |
return $this->uid; |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Generates a unique ID for the model. |
| 49 |
* |
| 50 |
* @since 3.16.0 |
| 51 |
* |
| 52 |
* @return string The generated unique ID. |
| 53 |
*/ |
| 54 |
abstract protected function generate_uid(): string; |
| 55 |
|
| 56 |
/** |
| 57 |
* Serializes the model to a JSON string. |
| 58 |
* |
| 59 |
* @since 3.16.0 |
| 60 |
* |
| 61 |
* @return string The serialized model. |
| 62 |
*/ |
| 63 |
public function serialize(): string { |
| 64 |
$json = wp_json_encode( $this->to_array() ); |
| 65 |
|
| 66 |
if ( false === $json ) { |
| 67 |
$json = '{}'; |
| 68 |
} |
| 69 |
|
| 70 |
return $json; |
| 71 |
} |
| 72 |
|
| 73 |
/** |
| 74 |
* Converts the model to an array. |
| 75 |
* |
| 76 |
* @since 3.16.0 |
| 77 |
* |
| 78 |
* @return array<mixed> The model as an array. |
| 79 |
*/ |
| 80 |
abstract public function to_array(): array; |
| 81 |
|
| 82 |
/** |
| 83 |
* Deserializes a JSON string to a model. |
| 84 |
* |
| 85 |
* @since 3.16.0 |
| 86 |
* |
| 87 |
* @param string $json The JSON string to deserialize. |
| 88 |
* @return Base_Model The deserialized model. |
| 89 |
*/ |
| 90 |
abstract public static function deserialize( string $json ): Base_Model; |
| 91 |
|
| 92 |
/** |
| 93 |
* Saves the model to the database. |
| 94 |
* |
| 95 |
* @since 3.16.0 |
| 96 |
* |
| 97 |
* @return bool True if the model was saved successfully, false otherwise. |
| 98 |
*/ |
| 99 |
abstract public function save(): bool; |
| 100 |
} |
| 101 |
|