| 1 |
<?php |
| 2 |
namespace Depicter\Document; |
| 3 |
|
| 4 |
|
| 5 |
use Depicter\Document\Models\Common\InnerStyles; |
| 6 |
use Depicter\Document\Models\Common\Styles; |
| 7 |
use Depicter\Document\Models\Common\Styles\Base as Style; |
| 8 |
use Depicter\Document\Models\Document; |
| 9 |
use TypeRocket\Utility\Data; |
| 10 |
|
| 11 |
/** |
| 12 |
* Maps JSON document data to document object |
| 13 |
* |
| 14 |
* @package Depicter\Document |
| 15 |
*/ |
| 16 |
class Mapper |
| 17 |
{ |
| 18 |
/** |
| 19 |
* @var Document |
| 20 |
*/ |
| 21 |
protected $document; |
| 22 |
|
| 23 |
/** |
| 24 |
* Hydrate the class with the provided $data. |
| 25 |
* |
| 26 |
* @param array|object $data |
| 27 |
* |
| 28 |
* @param int $documentId |
| 29 |
* |
| 30 |
* @return mixed Mapped object is returned. |
| 31 |
* @throws \JsonMapper_Exception |
| 32 |
*/ |
| 33 |
public function hydrate( $data, $documentId = 0 ) |
| 34 |
{ |
| 35 |
// Maybe convert to object |
| 36 |
$dataObject = Data::cast( $data, 'object'); |
| 37 |
|
| 38 |
// Hydrate the data to Document class |
| 39 |
$mapper = new \JsonMapper(); |
| 40 |
$mapper->undefinedPropertyHandler = function( $class, $propName, $jsonValue ){ |
| 41 |
if( $class instanceof Style ){ |
| 42 |
$class->{$propName} = $jsonValue; |
| 43 |
} |
| 44 |
|
| 45 |
if ( $class instanceof InnerStyles ) { |
| 46 |
$innerMapper = new \JsonMapper(); |
| 47 |
$jsonObject = Data::cast( $jsonValue, 'object'); |
| 48 |
$class->{$propName} = $innerMapper->map( $jsonObject, new Styles() ); |
| 49 |
} |
| 50 |
}; |
| 51 |
$documentObject = $dataObject->document ?? $dataObject; |
| 52 |
|
| 53 |
$baseMapper = function ($class, $jsonValue) { |
| 54 |
if ( is_array( $jsonValue ) && empty( $jsonValue ) ) { |
| 55 |
return null; |
| 56 |
} else { |
| 57 |
return '\Depicter\Document\Models\Common\Styles\Base'; |
| 58 |
} |
| 59 |
}; |
| 60 |
|
| 61 |
$mapper->classMap['\Depicter\Document\Models\Common\Styles\Base'] = $baseMapper; |
| 62 |
$this->document = $mapper->map( $documentObject, new Document() ); |
| 63 |
|
| 64 |
if( $documentId ){ |
| 65 |
$this->document->setDocumentID( $documentId ); |
| 66 |
} |
| 67 |
|
| 68 |
return $this; |
| 69 |
} |
| 70 |
|
| 71 |
/** |
| 72 |
* Retrieves the mapped Document object |
| 73 |
* |
| 74 |
* @return Document |
| 75 |
*/ |
| 76 |
public function get() |
| 77 |
{ |
| 78 |
return $this->document; |
| 79 |
} |
| 80 |
|
| 81 |
/** |
| 82 |
* @return string |
| 83 |
*/ |
| 84 |
public function render() |
| 85 |
{ |
| 86 |
return $this->get()->render(); |
| 87 |
} |
| 88 |
} |
| 89 |
|