model.php
62 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WPML\Templates\PHP; |
| 4 | |
| 5 | class Model { |
| 6 | private $attributes = []; |
| 7 | |
| 8 | public function __construct( $data = [] ) { |
| 9 | foreach ( $data as $key => $value ) { |
| 10 | $this->__set( $key, $value ); |
| 11 | } |
| 12 | } |
| 13 | |
| 14 | public function __get( $name ) { |
| 15 | if ( ! array_key_exists( $name, $this->attributes ) ) { |
| 16 | $this->attributes[ $name ] = new Model(); |
| 17 | } |
| 18 | |
| 19 | return $this->attributes[ $name ]; |
| 20 | } |
| 21 | |
| 22 | public function __set( $name, $value ) { |
| 23 | if ( is_object( $value ) ) { |
| 24 | $value = get_object_vars( $value ); |
| 25 | } |
| 26 | if ( is_array( $value ) ) { |
| 27 | $is_assoc = count( array_filter( array_keys( $value ), 'is_string' ) ) > 0; |
| 28 | if($is_assoc) { |
| 29 | $value = new Model( $value ); |
| 30 | } |
| 31 | } |
| 32 | $this->attributes[ $name ] = $value; |
| 33 | } |
| 34 | |
| 35 | public function hasValue( $name ) { |
| 36 | return ! $this->isNull( $name ) && ! $this->isEmpty( $name ); |
| 37 | } |
| 38 | |
| 39 | public function isNull( $name ) { |
| 40 | return $this->__get( $name ) === null; |
| 41 | } |
| 42 | |
| 43 | public function isEmpty( $name ) { |
| 44 | return $this->__get( $name ) === '' || ( ( $this->__get( $name ) instanceof Model ) && ! $this->__get( $name )->getAttributes() ); |
| 45 | } |
| 46 | |
| 47 | public function getAttributes() { |
| 48 | return $this->attributes; |
| 49 | } |
| 50 | |
| 51 | public function __toString() { |
| 52 | if ( count( $this->attributes ) === 0 ) { |
| 53 | return ''; |
| 54 | } |
| 55 | if ( count( $this->attributes ) === 1 ) { |
| 56 | return array_values( $this->attributes )[0]; |
| 57 | } |
| 58 | |
| 59 | return wp_json_encode( $this->attributes ); |
| 60 | } |
| 61 | } |
| 62 |