daily pastebin goal
91%
SHARE
TWEET

Untitled

a guest Oct 22nd, 2018 61 Never
Upgrade to PRO!
ENDING IN00days00hours00mins00secs
  1. <?php
  2.  
  3. namespace BlitzCommon\Hydrator;
  4.  
  5. use ReflectionClass;
  6. use Zend\Stdlib\Hydrator\HydratorInterface;
  7. use Zend\Stdlib\Exception;
  8.  
  9. class ReflectionObject implements HydratorInterface
  10. {
  11.     /**
  12.      * Simple in-memory array cache of ReflectionProperties used.
  13.      * @var array
  14.      */
  15.     static public $reflProperties = array();
  16.  
  17.     /**
  18.      * Extract values from an object
  19.      *
  20.      * @param  object $object
  21.      * @return array
  22.      */
  23.     public function extract($object)
  24.     {
  25.         $result = array();
  26.         foreach(self::getReflProperties($object) as $property) {
  27.             $result[$property->getName()] = $property->getValue($object);
  28.         }
  29.  
  30.         return $result;
  31.     }
  32.  
  33.     /**
  34.      * Hydrate $object with the provided $data.
  35.      *
  36.      * @param  array $data
  37.      * @param  object $object
  38.      * @return object
  39.      */
  40.     public function hydrate(array $data, $object)
  41.     {
  42.         $reflProperties = self::getReflProperties($object);
  43.         foreach($data as $key => $value) {
  44.             if (isset($reflProperties[$key])) {
  45.                 $reflProperties[$key]->setValue($object, $value);
  46.             }
  47.         }
  48.         return $object;
  49.     }
  50.  
  51.     /**
  52.      * Get a reflection properties from in-memory cache and lazy-load if
  53.      * class has not been loaded.
  54.      *
  55.      * @static
  56.      * @param string|object $object
  57.      * @return array
  58.      */
  59.     public static function getReflProperties($input)
  60.     {
  61.         if (is_object($input)) {
  62.             $input = get_class($input);
  63.         } else if (!is_string($input)) {
  64.             throw new Exception\InvalidArgumentException('Input must be a string or an object.');
  65.         }
  66.  
  67.         if (!isset(self::$reflProperties[$input])) {
  68.             $reflClass      = new ReflectionClass($input);
  69.             $reflProperties = $reflClass->getProperties();
  70.  
  71.             foreach($reflProperties as $key => $property) {
  72.                 $property->setAccessible(true);
  73.                 self::$reflProperties[$input][$property->getName()] = $property;
  74.             }
  75.         }
  76.  
  77.         return self::$reflProperties[$input];
  78.     }
  79. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top