2015-08-17 17:00:26 -07:00
< ? php
/**
* Zend Framework ( http :// framework . zend . com / )
*
* @ link http :// github . com / zendframework / zf2 for the canonical source repository
* @ copyright Copyright ( c ) 2005 - 2015 Zend Technologies USA Inc . ( http :// www . zend . com )
* @ license http :// framework . zend . com / license / new - bsd New BSD License
*/
2015-10-08 11:40:12 -07:00
namespace Zend\Hydrator ;
2015-08-17 17:00:26 -07:00
class ArraySerializable extends AbstractHydrator
{
/**
* Extract values from the provided object
*
* Extracts values via the object ' s getArrayCopy () method .
*
* @ param object $object
* @ return array
* @ throws Exception\BadMethodCallException for an $object not implementing getArrayCopy ()
*/
public function extract ( $object )
{
2015-10-08 11:40:12 -07:00
if ( ! is_callable ([ $object , 'getArrayCopy' ])) {
2015-08-17 17:00:26 -07:00
throw new Exception\BadMethodCallException (
sprintf ( '%s expects the provided object to implement getArrayCopy()' , __METHOD__ )
);
}
2015-10-08 11:40:12 -07:00
$data = $object -> getArrayCopy ();
2015-08-17 17:00:26 -07:00
$filter = $this -> getFilter ();
foreach ( $data as $name => $value ) {
if ( ! $filter -> filter ( $name )) {
unset ( $data [ $name ]);
continue ;
}
$extractedName = $this -> extractName ( $name , $object );
// replace the original key with extracted, if differ
if ( $extractedName !== $name ) {
unset ( $data [ $name ]);
$name = $extractedName ;
}
$data [ $name ] = $this -> extractValue ( $name , $value , $object );
}
return $data ;
}
/**
* Hydrate an object
*
* Hydrates an object by passing $data to either its exchangeArray () or
* populate () method .
*
* @ param array $data
* @ param object $object
* @ return object
* @ throws Exception\BadMethodCallException for an $object not implementing exchangeArray () or populate ()
*/
public function hydrate ( array $data , $object )
{
2015-10-08 11:40:12 -07:00
$replacement = [];
2015-08-17 17:00:26 -07:00
foreach ( $data as $key => $value ) {
$name = $this -> hydrateName ( $key , $data );
$replacement [ $name ] = $this -> hydrateValue ( $name , $value , $data );
}
2015-10-08 11:40:12 -07:00
if ( is_callable ([ $object , 'exchangeArray' ])) {
2015-08-17 17:00:26 -07:00
$object -> exchangeArray ( $replacement );
2015-10-08 11:40:12 -07:00
} elseif ( is_callable ([ $object , 'populate' ])) {
2015-08-17 17:00:26 -07:00
$object -> populate ( $replacement );
} else {
throw new Exception\BadMethodCallException (
sprintf ( '%s expects the provided object to implement exchangeArray() or populate()' , __METHOD__ )
);
}
return $object ;
}
}