Skip to content

Commit

Permalink
Allow to use an array with setMeta
Browse files Browse the repository at this point in the history
  • Loading branch information
fbraem committed Nov 30, 2021
1 parent 4a14aac commit 40c0129
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 5 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ All notable changes to 'Kwai\JSONAPI' will be documented here.

# 1.0.1
- Add id argument to JSONAPI\Resource attribute to allow other properties or a method to return the id.
- An array can be passed to setMeta

# 1.0.0
First release
16 changes: 11 additions & 5 deletions src/Document.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,21 @@ public static function createFromObject(object $obj): Document
}

/**
* Set a value in the meta object.
* Set value(s) in the meta object.
* When an array is passed, it will be merged with the current content
* of the meta object.
*
* @param string $key
* @param mixed $value
* @param string|array $keyOrArray
* @param mixed $value
* @return Document
*/
public function setMeta(string $key, mixed $value): Document
public function setMeta(string|array $keyOrArray, mixed $value = null): Document
{
$this->meta[$key] = $value;
if (is_array($keyOrArray)) {
$this->meta = array_merge($this->meta, $keyOrArray);
} else {
$this->meta[$keyOrArray] = $value;
}
return $this;
}

Expand Down
81 changes: 81 additions & 0 deletions tests/MetaTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,84 @@
])
;
});

it('can set meta with an array', function () {
$person = new Person(
id: '1',
name: 'Jigoro Kano',
age: 77
);

try {
$jsonapi =
JSONAPI\Document::createFromObject($person)
->setMeta([
'count' => 1,
'limit' => 10,
'offset' => 0
])
->serialize();
} catch (JSONAPI\Exception $e) {
$this->fail((string) $e);
}

$json = json_decode($jsonapi);

expect($json)
->toMatchObject([
'meta' => (object) [
'count' => 1,
'limit' => 10,
'offset' => 0
],
'data' => (object) [
'type' => 'people',
'id' => '1',
'attributes' => (object) [
'name' => 'Jigoro Kano',
'age' => 77
]
]
])
;
});

it('can set meta one by one', function () {
$person = new Person(
id: '1',
name: 'Jigoro Kano',
age: 77
);

try {
$jsonapi =
JSONAPI\Document::createFromObject($person)
->setMeta('count', 1)
->setMeta('limit', 10)
->setMeta('offset', 0)
->serialize();
} catch (JSONAPI\Exception $e) {
$this->fail((string) $e);
}

$json = json_decode($jsonapi);

expect($json)
->toMatchObject([
'meta' => (object) [
'count' => 1,
'limit' => 10,
'offset' => 0
],
'data' => (object) [
'type' => 'people',
'id' => '1',
'attributes' => (object) [
'name' => 'Jigoro Kano',
'age' => 77
]
]
])
;
});

0 comments on commit 40c0129

Please sign in to comment.