PHP code example of php-grape / grape-entity

1. Go to this page and download the library: Download php-grape/grape-entity library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

php-grape / grape-entity example snippets


class StatusEntity extends Entity
{
  use EntityTrait;

  private static function initialize()
  {
    self::formatWith('iso_timestamp', function($dt) {
      return $dt->format(DateTime::ISO8601);
    });

    self::expose('user_name');
    self::expose('text', [
      'documentation' => ['type' => 'String', 'desc' => 'Status update text'
    ]);
    self::expose('ip', ['if' => ['type' => 'full']]);
    self::expose('user_type', 'user_id', ['if' => function($status, $options) {
      return $status->user->isPublic();
    }]);
    self::expose('location', ['merge' => true]);
    self::expose('contact_info', function() {
      self::expose('phone');
      self::expose('address', ['merge' => true, 'using' => AddressEntity::class]);
    });
    self::expose('digest', function($status, $options) {
      return md5($status->text);
    });
    self::expose('replies', ['as' => 'responses', 'using' => StatusEntity::class]);
    self::expose('last_reply', ['using' => StatusEntity::class], function($status, $options) {
      return $status->replies->last;
    });

    self::withOptions(['format_with' => 'iso_timestamp'], function() {
      self::expose('created_at');
      self::expose('updated_at');
    });
  }
}

class StatusDetailedEntity extends Entity
{
  use EntityTrait;

  private static function initialize()
  {
    self::extends(StatusEntity::class);

    self::expose('internal_id');
  }
}

class AEntity extends Entity
{
  use EntityTrait;

  // `initialized` will be called automatically when needed :)
  private static function initialize()
  {
    self::extends(BEntity::class, CEntity::class, DEntity::class);
  
    ...
  }
}

self::expose('user_name', 'ip');

use PhpGrape\Reflection;

Reflection::$disableProtectedProps = true;
Reflection::$disablePrivateProps = true;
Reflection::$disableProtectedMethods = true;
Reflection::$disablePrivateMethods = true;

class StatusEntity extends Entity
{
  use EntityTrait;

  private static function initialize()
  {
    self::expose('code');
    self::expose('message');
  }
}

$representation = StatusEntity::represent(['code' => 418, 'message' => "I'm a teapot"]);
json_encode($representation); // => { code: 418, message: "I'm a teapot" }

self::expose('replies', ['as' => 'responses', 'using' => StatusEntity::class]);

self::expose('ip', ['if' => ['type' => 'full']]);

// Exposed if the function evaluates to true
self::expose('ip', ['if' => function($instance, $options) {
  return isset($options['type']) && $options['type'] === 'full';
}]);

// Exposed if 'type' is set in the options array and is truthy
self::expose('ip', ['if' => 'type']);

// Exposed if $options['type'] is set and equals 'full'
self::expose('ip', ['if' => ['type' => 'full']]);

self::('expose', 'ip', ['safe' => true]);

self::expose('contact_info', function() {
  self::expose('phone');
  self::expose('address', ['using' => Addressentity::class]);
});

self::expose('contact_info', function() {
  self::expose('phone')
  self::expose('address', ['using' => AddressEntity::class]);
  self::expose('email', ['if' => ['type' => 'full']);
});

self::root('users', 'user');
self::expose('id', 'name');

// `collection_name` is optional and defaults to `items`
self::presentCollection(true, 'collection_name');
self::expose('collection_name', ['using' => ItemEntity::class]);

self::expose('contact_info', function() {
  self::expose('phone');
  self::expose('address', ['merge' => true, 'using' => AddressEntity::class]);
});

self::expose('status', ['merge' => true]);

{ contact_info: { phone: "88002000700", city: 'City 17', address_line: 'Block C' }, text: 'HL3', likes: 19 }

self::expose('profiles', function() {
  self::expose('users', ['merge' => true, 'using' => UserEntity::class]);
  self::expose('admins', ['merge' => true, 'using' => AdminEntity::class]);
});

self::expose('status', ['merge' => function($key, $oldVal, $newVal) { 
  // You don't need to check if $oldVal is set here
  return $oldVal && $newVal ? $oldVal + $newVal : null;
}]);

self::expose('digest', function($status, $options) {
  return md5($status->txt);
});

// equivalent
function getDigest($status, $options) {
  return md5($status->txt);
}

...

self::expose('digest', ['func' => 'getDigest']);

class ExampleEntity extends Entity
{
  use EntityTrait;

  private static function initialize()
  {
    self::expose('attr_not_on_wrapped_object');
  }

  private function attr_not_on_wrapped_object()
  {
    return 42;
  }
}

class ExampleEntity extends Entity
{
  use EntityTrait;

  private static function initialize()
  {
    self::expose('formatted_value');
  }
  
  private function formatted_value()
  {
    return "+ X {$this->object->value} {$this->options['y']}"
  }
}

class UserEntity extends Entity
{
  use EntityTrait;

  private static function initialize()
  {
    self::expose('name');
    self::expose('address1');
    self::expose('address2');
    self::expose('address_state');
    self::expose('address_city');
    self::expose('email');
    self::expose('phone');
  }
}

class MailingEntity extends Entity
{
  use EntityTrait;

  private static function initialize()
  {
    self::extends(UserEntity::class);
  
    self::unexpose('email');
    self::unexpose('phone');
  }
}

class UserEntity extends Entity
{
  use EntityTrait;

  private static function initialize()
  {
    self::expose('name');
  }
}

class EmployeeEntity extends Entity
{
  use EntityTrait;

  private static function initialize()
  {
    self::extends(UserEntity::class);

    self::expose('name', ['as' => 'employe_name', 'override' => true]);
  }
}

class UserEntity extends Entity
{
  use EntityTrait;

  private static function initialize()
  {
    self::expose('id');
    self::expose('name');
    self::expose('email');
  }
}

class ExampleEntity extends Entity
{
  use EntityTrait;

  private static function initialize()
  {
    self::expose('id');
    self::expose('title');
    self::expose('user', ['using' => UserEntity::class]);
  }
}

$data = ExampleEntity::represent($model, [
  'only' => ['title', ['user' => ['name', 'email']]]
]);
json_encode($data);

{
  title: 'grape-entity is awesome!',
  user: {
  name: 'John Doe',
  email: '[email protected]'
  }
}

$data = ExampleEntity::represent($model, 
  'except' => ['id', ['user' => 'id']]
);
json_encode($data);

self::expose('replies', ['as' => 'responses', 'using' => StatusEntity::class]);

class MyEntity extends Entity
{
  use EntityTrait;

  private static function initialize()
  {
    self::formatWith('iso_timestamp', function($dt) {
      return $dt->format(DateTime::ISO8601);
    });

    self::withOptions(['format_with' => 'iso_timestamp'], function() {
      self::expose('created_at');
      self::expose('updated_at');
    });
  }
}

Entity::formatWith('utc', function($dt) {
  return $dt->setTimezone(new DateTimeZone('UTC'));
});

class AnotherEntity extends Entity
{
  use EntityTrait;

  private static function initialize()
  {
    self::expose('created_at', ['format_with' => 'utc']);
  }
}

[
  'name' => null,
  'age' => 100
]

class MyEntity extends Entity
{
  use EntityTrait;

  private static function initialize()
  {
    self::expose('name', ['expose_null' => false]);
    self::expose('age', ['expose_null' => false]);
  }
}

class MyEntity extends Entity
{
  use EntityTrait;

  private static function initialize()
  {
    self::expose('name', ['expose_null' => false]);
    // since expose_null is omitted null values will be rendered
    self::expose('age');
  }
}

class MyEntity extends Entity
{
  use EntityTrait;

  private static function initialize()
  {
    // None of the exposures in the withOptions closure will render null values
    self::withOptions(['expose_null' => false], function() {
      self::expose('name');
      self::expose('age');
    });
  }
}

class MyEntity extends Entity
{
  use EntityTrait;

  private static function initialize()
  {
    // None of the exposures in the withOptions closure will render null values
    self::withOptions(['expose_null' => false], function() {
      self::expose('name');
      // null values would be rendered in the JSON
      self::expose('age', ['expose_null' => true]);
    });
  }
}

class MyEntity extends Entity
{
  use EntityTrait;

  private static function initialize()
  {
    self::expose('name', ['default' => '']);
    self::expose('age', ['default' => 60]);
  }
}

self::expose('text', [
  'documentation' => ['type' => 'String', 'desc' => "Status update text."]
]);

class MyEntity extends Entity
{
  use EntityTrait;

  private static function initialize()
  {
    self::expose('user', ['if' => function($instance, $options) {
      return isset($options['user']);
    }], function($instance, $options) {
      return $options['user'];
    });
  }
}

MyEntity::represent($s, ['using' => StatusEntity::class, 'user' => current_user()]);

// api/ContactEntity.php
self::expose('contact_info', function() {
  self::expose('phone');
  self::expose('address', function($instance, $options) {
  // use `array_merge` to extend options and then pass the new version of options to the nested entity
  $options = array_merge(['full_format' => $instance->needFullFormat()], $options);
    return AddressEntity::represent($instance->address, $options);
  });
  self::expose('email', ['if' => ['type' => 'full']]);
}

// api/AddressEntity.php
// the new option could be retrieved in options array for conditional exposure
self::expose('state', ['if' => 'full_format']);
self::expose('city', ['if' => 'full_format']);
self::expose('street', function($instance, $options) {
  // the new option could be retrieved in options hash for runtime exposure
  return $options['full_format'] ? $instance->full_street_name : $instance->simple_street_name;
});

class MyEntity extends Entity
{
  use EntityTrait;

  private static function initialize()
  {
    self::expose('user');  // path is ['user']
    self::expose('foo', ['as' => 'bar']);  // path is ['bar']
    self::expose('a', function() {
      self::expose('b', ['as' => 'xx'], function() {
      self::expose('c');  // path is ['a', 'xx', 'c']
      });
    });
  }
}

class ApiController
{
  use UserHelpers;  
  
  public function statuses()
  {
    $statuses = Status::all();
    $type = $this->user()->isAdmin() ? 'full' : 'default';
    $representation = StatusEntity::represent($statuses, ['type' => $type]);

    // PhpGrape\Entity implements JsonSerializable
    return response()->json($representation, 200);
  }
}

json_encode(new MyEntity($myObj))
json_encode(MyEntity::represent($myObj))

new MyEntity($myObj)->toJson();
new MyEntity($myObj)->toXml();

Entity::transformKeys(function($key) {
   return mb_strtoupper($key);
});

Entity::transformKeys('camel');

class MyEntity extends Entity
{
  use EntityTrait;

  private static function initialize()
  {
    self::root('current_user');
    self::expose('first_name', ['documentation' => ['desc' => 'foo']]);
  }
}

$representation = MyEntity::represent(['first_name' => 'John']);
json_encode($representation); // { currentUser: { firstName: 'John' } }
json_encode(MyEntity::documentation()); // { firstName: { desc: 'foo' } }

// Entity used is binded to $this 
//   so you have access to $this->object and $this->options
Entity::setPropValueAdapter('MyAdapter', [
  'condition' => function ($prop, $safe) {
    $model = 'MyProject\MyModel';
    return $this->object instanceof $model;
  },
  'getPropValue' => function ($prop, $safe, $cache) {
    $class = get_class($this->object);
  
    // you can use $cache to speed up future lookups
    if ($cache('get', $class, $prop)) return $this->object->{$prop};
  
    if ($this->object->hasAttribute($prop)) {
      $cache('set', $class, $prop);
      return $this->object->{$prop};
    }
  
    // Prop not found
    return $this->handleMissingProperty($prop, $safe);
  }
]);

Entity::setPropValueAdapter('MyAdapter', null);

  composer