| 1 |
<?php |
| 2 |
/** |
| 3 |
* DTO |
| 4 |
* |
| 5 |
* @package SeQura/WC/ |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace SeQura\WC\Dto; |
| 9 |
|
| 10 |
use ValueError; |
| 11 |
|
| 12 |
/** |
| 13 |
* DTO. |
| 14 |
*/ |
| 15 |
abstract class Dto { |
| 16 |
|
| 17 |
/** |
| 18 |
* Decode a raw string into a DTO instance. By default, assumes that the raw string is a JSON string. |
| 19 |
* |
| 20 |
* @return static|null |
| 21 |
*/ |
| 22 |
public static function decode( string $raw ) { |
| 23 |
try { |
| 24 |
$data = json_decode( $raw, true ); |
| 25 |
} catch ( ValueError $e ) { // @phpstan-ignore-line |
| 26 |
return null; |
| 27 |
} |
| 28 |
if ( ! is_array( $data ) ) { |
| 29 |
return null; |
| 30 |
} |
| 31 |
$instance = new static(); // @phpstan-ignore-line |
| 32 |
foreach ( $data as $key => $value ) { |
| 33 |
if ( property_exists( $instance, $key ) ) { |
| 34 |
$instance->$key = $value; |
| 35 |
} |
| 36 |
} |
| 37 |
return $instance; |
| 38 |
} |
| 39 |
|
| 40 |
/** |
| 41 |
* Create a DTO instance from an array. |
| 42 |
* |
| 43 |
* @param array<string, mixed> $data |
| 44 |
* @return static|null |
| 45 |
*/ |
| 46 |
public static function from_array( array $data ) { |
| 47 |
if ( ! is_array( $data ) ) { |
| 48 |
return null; |
| 49 |
} |
| 50 |
$instance = new static(); // @phpstan-ignore-line |
| 51 |
foreach ( $data as $key => $value ) { |
| 52 |
if ( property_exists( $instance, $key ) ) { |
| 53 |
$instance->$key = $value; |
| 54 |
} |
| 55 |
} |
| 56 |
return $instance; |
| 57 |
} |
| 58 |
|
| 59 |
/** |
| 60 |
* Convert the DTO instance into an array. |
| 61 |
* |
| 62 |
* @return array<string, mixed> |
| 63 |
*/ |
| 64 |
public function to_array(): array { |
| 65 |
return (array) $this; |
| 66 |
} |
| 67 |
|
| 68 |
/** |
| 69 |
* Encode the DTO instance into a raw string. By default, returns a JSON string. |
| 70 |
*/ |
| 71 |
public function encode(): string { |
| 72 |
$encoded = \wp_json_encode( $this, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); |
| 73 |
return $encoded ? $encoded : ''; |
| 74 |
} |
| 75 |
} |
| 76 |
|