diff --git "a/class-wb\\DataModel.php" "b/class-wb\\DataModel.php" index 03098ea..5bdd174 100644 --- "a/class-wb\\DataModel.php" +++ "b/class-wb\\DataModel.php" @@ -1,112 +1,127 @@ . # Wikibase namespace wb; class DataModel { private $labels; private $descriptions; private $claims; public function __construct() { $this->labels = new Labels(); $this->descriptions = new Descriptions(); $this->claims = new Claims(); } public function getLabels() { return $this->labels->getAll(); } public function getDescriptions() { return $this->descriptions->getAll(); } public function getClaims() { return $this->claims->getAll(); } public function addClaim( $claim ) { $this->claims->add( $claim ); return $this; } public function setClaims( $claims ) { $this->claims->set( $claims ); return $this; } public function hasClaimsInProperty( $property ) { return $this->claims->haveProperty( $property ); } public function countClaims() { return $this->claims->count(); } /** * Set, delete, preserve if it exists, a label. */ public function setLabel( $label ) { $this->labels->set( $label ); return $this; } /** * Set, delete, preserve if it exists, a description. */ public function setDescription( $description ) { $this->descriptions->set( $description ); return $this; } public function get() { return [ 'labels' => $this->getLabels(), 'descriptions' => $this->getDescriptions(), 'claims' => $this->getClaims() ]; } public function getJSON( $args = null ) { return json_encode( $this->get(), $args ); } public static function createFromData( $data ) { $dataModel = new self(); - if( isset( $data['labels'] ) ) { + if( ! empty( $data['labels'] ) ) { foreach( $data['labels'] as $label ) { $dataModel->setLabel( Label::createFromData( $label ) ); } } - if( isset( $data['descriptions'] ) ) { + if( ! empty( $data['descriptions'] ) ) { foreach( $data['descriptions'] as $description ) { $dataModel->setDescription( Description::createFromData( $description ) ); } } - if( isset( $data['claims'] ) ) { + if( ! empty( $data['claims'] ) ) { foreach( $data['claims'] as $claims ) { foreach( $claims as $claim ) { $dataModel->addClaim( Claim::createFromData( $claim ) ); } } } return $dataModel; } + + public static function createFromObject( $object ) { + return self::createFromData( self::object2array( $object ) ); + } + + private static function object2array( $object ) { + if( ! is_object( $object) && ! is_array( $object ) ) { + return $object; + } + $array = []; + foreach( $object as $k => $v ) { + $array[ $k ] = self::object2array( $v ); + } + return $array; + } }