Advertisement
Guest User

Untitled

a guest
Apr 30th, 2014
323
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.07 KB | None | 0 0
  1. <?php
  2. /**
  3.  * Class JsonData
  4.  *
  5.  * Example:
  6.  *    return [
  7.  *        'some_items' => (new JsonData(Some::all()))
  8.  *            ->with(['id', 'message', 'created_at'])
  9.  *            ->child('user', ['id', 'login', 'photo'])
  10.  *            ->render()
  11.  *    ];
  12.  *
  13.  */
  14. class JsonData
  15. {
  16.     /**
  17.      * Source object
  18.      * @var
  19.      */
  20.     private $_object;
  21.  
  22.     /**
  23.      * Filters
  24.      * @var array
  25.      */
  26.     private $_filters = [];
  27.  
  28.     /**
  29.      * Children objects
  30.      * @var array
  31.      */
  32.     private $_children = [];
  33.  
  34.     /**
  35.      * @param $object
  36.      */
  37.     public function __construct($object)
  38.     {
  39.         $this->_object = $object;
  40.     }
  41.  
  42.     /**
  43.      * Add filter
  44.      * @param $names
  45.      * @return $this
  46.      */
  47.     public function with($names)
  48.     {
  49.         if (!is_array($names)) {
  50.             $names = [$names];
  51.         }
  52.         foreach ($names as $name) {
  53.             $this->_filters[] = $name;
  54.         }
  55.         return $this;
  56.     }
  57.  
  58.     /**
  59.      * Add child
  60.      * @param $name
  61.      * @param $attrs
  62.      * @return $this
  63.      */
  64.     public function child($name, $attrs)
  65.     {
  66.         $this->_children[$name] = $attrs;
  67.         return $this;
  68.     }
  69.  
  70.     /**
  71.      * Parse data
  72.      * @return array
  73.      */
  74.     protected function getResult()
  75.     {
  76.         $createItem = function($item)
  77.         {
  78.             $response = [];
  79.             foreach ($this->_filters as $f) {
  80.                 $response[$f] = $item->$f;
  81.             }
  82.  
  83.             foreach ($this->_children as $child => $attrs) {
  84.                 $response[$child] = [];
  85.                 foreach ($attrs as $attr) {
  86.                     $response[$child][$attr] = $item->$child->$attr;
  87.                 }
  88.             }
  89.             return $response;
  90.         };
  91.  
  92.         $result = [];
  93.         foreach ($this->_object as $item) {
  94.             $result[] = $createItem($item);
  95.         }
  96.         return $result;
  97.     }
  98.  
  99.     /**
  100.      * Return result
  101.      * @return array
  102.      */
  103.     public function render()
  104.     {
  105.         return $this->getResult();
  106.     }
  107. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement