class-dto.php
91 lines
| 1 | <?php |
| 2 | /** |
| 3 | * The data transfer object class file. |
| 4 | * |
| 5 | * @package GenerateBlocks\Utils |
| 6 | */ |
| 7 | |
| 8 | if ( ! defined( 'ABSPATH' ) ) { |
| 9 | exit; // Exit if accessed directly. |
| 10 | } |
| 11 | |
| 12 | /** |
| 13 | * The GenerateBlocks Data Transfer Object class. |
| 14 | * |
| 15 | * @since 1.9.0 |
| 16 | */ |
| 17 | class GenerateBlocks_DTO implements JsonSerializable { |
| 18 | /** |
| 19 | * The data. |
| 20 | * |
| 21 | * @var array The DTO data. |
| 22 | */ |
| 23 | protected $data = array(); |
| 24 | |
| 25 | /** |
| 26 | * Returns the data values if exists. |
| 27 | * |
| 28 | * @param string $name The called name. |
| 29 | * |
| 30 | * @return string|null |
| 31 | */ |
| 32 | public function __get( string $name ): ?string { |
| 33 | return $this->data[ $name ] ?? null; |
| 34 | } |
| 35 | |
| 36 | /** |
| 37 | * Set a value for the DTO data. |
| 38 | * |
| 39 | * @param string $key The name. |
| 40 | * @param mixed $value The value. |
| 41 | * |
| 42 | * @return GenerateBlocks_DTO |
| 43 | */ |
| 44 | public function set( string $key, $value ): GenerateBlocks_DTO { |
| 45 | if ( isset( $this->data[ $key ] ) ) { |
| 46 | $this->data[ $key ] = $value; |
| 47 | } |
| 48 | |
| 49 | return $this; |
| 50 | } |
| 51 | |
| 52 | /** |
| 53 | * Serialize this class. |
| 54 | * |
| 55 | * @return array |
| 56 | */ |
| 57 | public function serialize(): array { |
| 58 | $result = array(); |
| 59 | |
| 60 | foreach ( $this->data as $key => $value ) { |
| 61 | $k = generateblocks_to_camel_case( $key ); |
| 62 | $result[ $k ] = $value; |
| 63 | } |
| 64 | |
| 65 | return $result; |
| 66 | } |
| 67 | |
| 68 | /** |
| 69 | * Unserialize this class. |
| 70 | * |
| 71 | * @param array $data The data. |
| 72 | * |
| 73 | * @return void |
| 74 | */ |
| 75 | public function unserialize( array $data ): void { |
| 76 | foreach ( $data as $key => $value ) { |
| 77 | $k = generateblocks_to_snake_case( $key ); |
| 78 | $this->data[ $k ] = $value; |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | /** |
| 83 | * JSON serialize function. |
| 84 | * |
| 85 | * @return array |
| 86 | */ |
| 87 | public function JsonSerialize(): array { |
| 88 | return $this->serialize(); |
| 89 | } |
| 90 | } |
| 91 |