PluginProbe
seQura / trunk
seQura vtrunk
4.3.4 4.3.3 4.3.2 4.3.1 trunk 2.0.0 2.0.10 2.0.11 2.0.12 2.0.5 2.0.6 2.0.7 2.0.8 2.0.9 3.0.0 3.0.2 3.0.5 3.0.6 3.0.7 3.1.0 3.1.1 3.2.0 3.2.1 3.2.2 4.0.0 All 30 releases
sequra / src / Dto / class-dto.php

class-dto.php in seQura trunk, at src/Dto/class-dto.php

76 lines 1.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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