Skip to content

Commit

Permalink
Fields - add docs (#13)
Browse files Browse the repository at this point in the history
* Create fields.md

* Update QueryInterpreter.php
  • Loading branch information
jorisatabix authored Feb 18, 2020
1 parent c37cb3c commit cd2cbe2
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 2 deletions.
71 changes: 71 additions & 0 deletions docs/fields.md
Original file line number Diff line number Diff line change
@@ -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),
];
}
}
```
4 changes: 2 additions & 2 deletions src/Apitizer/Interpreter/QueryInterpreter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit cd2cbe2

Please sign in to comment.