Skip to content

[2.1] Add conditional props #14

@jodiedunlop

Description

@jodiedunlop

Allow conditionally including props. This would allow easily implementing ACL checks, or to prevent props from being included under certain environments.

isPropVisible()

Allow transformers to (optionally) implement isPropVisible() to conditionally include props in the transformed result

  • Signature would be something like isPropVisible(string $prop, Scope $scope): bool
  • Transformers can have dependencies injected via their constructor (such as a $user object) and refer to these

Example:

class UserTransformer extends Transformer
{
    protected $authUser;

    protected $props = [
         'id',
         'email',
         'dob',
    ];

   public function __construct(User $user)
    {
        $this->authUser = $user;
    }

    protected function isPropVisible($prop)
    {
        if ($prop === 'dob' && !$this->authUser->isHumanResources()) {
            // only HR reps can see date of birth
            return false;
        }

         return true;
    }      
}

Delarative prop: when

In addition, declarative props should also support a new when: directive which specifies a method to handle the visibility.

  • The method must be located on the transformer object
  • Can optionally include parenthesis, where anything inside the parens will be passed as the first argument to the method
    • support auto-casting of true, false, null, and any plain integer eg. 123

Example:

class UserTransformer extends Transformer
{
    protected $authUser;

    protected $props = [
         'id',
         'email',
         'dob|when:hasRole(admin)',
    ];

   public function __construct(User $user)
    {
        $this->authUser = $user;
    }

    protected function hasRole($role, $prop, Scope $scope)
    {
        return $this->authUser->hasRole($role);
    }      
}

Happy for feedback / alternative implementations

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions