Skip to content

Commit 82f9cda

Browse files
committed
Add ability to make a field sparse by default
1 parent 58135ea commit 82f9cda

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed

src/Context.php

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -109,11 +109,16 @@ public function sparseFields(Resource $resource): array
109109
}
110110

111111
$fields = $this->fields($resource);
112+
$type = $resource->type();
113+
$fieldsParam = $this->queryParam('fields');
112114

113-
if ($requested = $this->queryParam('fields')[$resource->type()] ?? null) {
115+
if (is_array($fieldsParam) && array_key_exists($type, $fieldsParam)) {
116+
$requested = $fieldsParam[$type];
114117
$requested = is_array($requested) ? $requested : explode(',', $requested);
115118

116119
$fields = array_intersect_key($fields, array_flip($requested));
120+
} else {
121+
$fields = array_filter($fields, fn(Field $field) => !$field->sparse);
117122
}
118123

119124
return $this->sparseFields[$resource] = $fields;
@@ -122,13 +127,15 @@ public function sparseFields(Resource $resource): array
122127
/**
123128
* Determine whether a field has been requested in a sparse fieldset.
124129
*/
125-
public function fieldRequested(string $type, string $field, bool $default = true): bool
130+
public function fieldRequested(string $type, string $field): bool
126131
{
127-
if ($requested = $this->queryParam('fields')[$type] ?? null) {
128-
return in_array($field, explode(',', $requested));
132+
$fieldsParam = $this->queryParam('fields');
133+
134+
if (is_array($fieldsParam) && array_key_exists($type, $fieldsParam)) {
135+
return in_array($field, explode(',', $fieldsParam[$type]));
129136
}
130137

131-
return $default;
138+
return !($this->fields($this->resource($type))[$field]?->sparse ?? null);
132139
}
133140

134141
/**

src/Schema/Field/Field.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ abstract class Field
1818
public bool $nullable = false;
1919
public ?string $description = null;
2020
public array $schema = [];
21+
public bool $sparse = false;
2122

2223
public function __construct(public readonly string $name)
2324
{
@@ -57,4 +58,14 @@ public function getSchema(JsonApi $api): array
5758
'readOnly' => !$this->writable,
5859
];
5960
}
61+
62+
/**
63+
* Only include this field if it is specifically requested.
64+
*/
65+
public function sparse(): static
66+
{
67+
$this->sparse = true;
68+
69+
return $this;
70+
}
6071
}

0 commit comments

Comments
 (0)