Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Class JsonData
- *
- * Example:
- * return [
- * 'some_items' => (new JsonData(Some::all()))
- * ->with(['id', 'message', 'created_at'])
- * ->child('user', ['id', 'login', 'photo'])
- * ->render()
- * ];
- *
- */
- class JsonData
- {
- /**
- * Source object
- * @var
- */
- private $_object;
- /**
- * Filters
- * @var array
- */
- private $_filters = [];
- /**
- * Children objects
- * @var array
- */
- private $_children = [];
- /**
- * @param $object
- */
- public function __construct($object)
- {
- $this->_object = $object;
- }
- /**
- * Add filter
- * @param $names
- * @return $this
- */
- public function with($names)
- {
- if (!is_array($names)) {
- $names = [$names];
- }
- foreach ($names as $name) {
- $this->_filters[] = $name;
- }
- return $this;
- }
- /**
- * Add child
- * @param $name
- * @param $attrs
- * @return $this
- */
- public function child($name, $attrs)
- {
- $this->_children[$name] = $attrs;
- return $this;
- }
- /**
- * Parse data
- * @return array
- */
- protected function getResult()
- {
- $createItem = function($item)
- {
- $response = [];
- foreach ($this->_filters as $f) {
- $response[$f] = $item->$f;
- }
- foreach ($this->_children as $child => $attrs) {
- $response[$child] = [];
- foreach ($attrs as $attr) {
- $response[$child][$attr] = $item->$child->$attr;
- }
- }
- return $response;
- };
- $result = [];
- foreach ($this->_object as $item) {
- $result[] = $createItem($item);
- }
- return $result;
- }
- /**
- * Return result
- * @return array
- */
- public function render()
- {
- return $this->getResult();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement