Allow fields to be made only visible for single root resources

This commit is contained in:
Toby Zerner 2019-10-03 16:32:18 +09:30
parent 8ae0682d3a
commit 606a79a0cf
3 changed files with 26 additions and 4 deletions

View File

@ -35,7 +35,7 @@ class Show implements RequestHandlerInterface
$serializer = new Serializer($this->api, $request);
$serializer->add($this->resource, $this->model, $include);
$serializer->add($this->resource, $this->model, $include, true);
return new JsonApiResponse(
new CompoundDocument(

View File

@ -14,6 +14,7 @@ abstract class Field
private $name;
private $property;
private $visible = true;
private $single = false;
private $writable = false;
private $getter;
private $setter;
@ -49,6 +50,18 @@ abstract class Field
return $this;
}
/**
* Indicates that the field should only be visible on single root resources
*
* @return $this
*/
public function single()
{
$this->single = true;
return $this;
}
public function writable(Closure $condition = null)
{
$this->writable = $condition ?: true;
@ -137,6 +150,11 @@ abstract class Field
return $this->visible;
}
public function getSingle()
{
return $this->single;
}
public function getWritable()
{
return $this->writable;

View File

@ -30,14 +30,14 @@ final class Serializer
$this->request = $request;
}
public function add(ResourceType $resource, $model, array $include)
public function add(ResourceType $resource, $model, array $include, bool $single = false)
{
$data = $this->addToMap($resource, $model, $include);
$data = $this->addToMap($resource, $model, $include, $single);
$this->primary[] = $data['type'].':'.$data['id'];
}
private function addToMap(ResourceType $resource, $model, array $include)
private function addToMap(ResourceType $resource, $model, array $include, bool $single = false)
{
$adapter = $resource->getAdapter();
$schema = $resource->getSchema();
@ -69,6 +69,10 @@ final class Serializer
continue;
}
if ($field->getSingle() && ! $single) {
continue;
}
if (! evaluate($field->getVisible(), [$model, $this->request])) {
continue;
}