From cd2cbe2b5451ba5605c1df6bf33dd06a374ba4ae Mon Sep 17 00:00:00 2001 From: Joris Kok <36499489+jorisatabix@users.noreply.github.com> Date: Tue, 18 Feb 2020 13:32:55 +0100 Subject: [PATCH] Fields - add docs (#13) * Create fields.md * Update QueryInterpreter.php --- docs/fields.md | 71 +++++++++++++++++++ src/Apitizer/Interpreter/QueryInterpreter.php | 4 +- 2 files changed, 73 insertions(+), 2 deletions(-) create mode 100644 docs/fields.md diff --git a/docs/fields.md b/docs/fields.md new file mode 100644 index 0000000..126ef66 --- /dev/null +++ b/docs/fields.md @@ -0,0 +1,71 @@ +# Fields + + +Look at the `HasFields` trait for all available types (string, int etc). + +## Example + +``` +class DamageBuilder extends QueryBuilder +{ + public function fields(): array + { + return [ + 'id' => $this->uuid('uuid'), + 'name' => $this->string('name')->nullable(), + 'created_at' => $this->datetime('created_at'), + 'updated_at' => $this->datetime('updated_at'), + ]; + } +} +``` + +## Custom types + +Extend the QueryBuilder to modify or add specific types. Here we want the string to return an empty string `""`, instead of a `null` (for backwards compatiblity) + +```php +abstract class QueryBuilder extends \Apitizer\QueryBuilder +{ + protected function string(string $key): Field + { + return $this->field($key, 'string')->transform(static function ($value) { + // Always cast to string, even if null, because of backwards compatibility + return (string) $value; + }); + } +} +``` + + +## Callable fields + + +```php +use Apitizer\Types\GeneratedField; + +class InvoiceBuilder { + public function fields(): array + { + return [ + 'total' => $this->generatedField('int', function ($row, GeneratedField $field) { + return 1; + }); + ]; + } +} +``` + +Any `callable` is accepted, so something like this would also suffice: +```php +use Apitizer\Types\GeneratedField; + +class InvoiceBuilder { + public function fields(): array + { + return [ + 'total' => $this->generatedField('int', new CalculateOrderTotal), + ]; + } +} +``` diff --git a/src/Apitizer/Interpreter/QueryInterpreter.php b/src/Apitizer/Interpreter/QueryInterpreter.php index b3962cd..4f75c8c 100644 --- a/src/Apitizer/Interpreter/QueryInterpreter.php +++ b/src/Apitizer/Interpreter/QueryInterpreter.php @@ -4,7 +4,7 @@ use Apitizer\Types\FetchSpec; use Apitizer\QueryBuilder; -use Apitizer\Types\AbstractField; +use Apitizer\Types\Field; use Apitizer\Types\Association; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Relations\BelongsTo; @@ -42,7 +42,7 @@ private function applySelect(Builder $query, array $fields, array $additionalSel $selectKeys = array_merge([$query->getModel()->getKeyName()], $additionalSelects); foreach ($fields as $fieldOrAssoc) { - if ($fieldOrAssoc instanceof AbstractField) { + if ($fieldOrAssoc instanceof Field) { // Also load any of the selected keys. $selectKeys[] = $fieldOrAssoc->getKey(); } else if ($fieldOrAssoc instanceof Association) {