Accept callback to get nested type of rule for Document arrays

This commit is contained in:
kodumbeats 2021-08-27 13:09:56 -04:00
parent 2ead9c52f6
commit 87de870093
2 changed files with 12 additions and 4 deletions

View file

@ -340,11 +340,12 @@ class Response extends SwooleResponse
foreach ($data[$key] as &$item) {
if ($item instanceof Document) {
if (!array_key_exists($rule['type'], $this->models)) {
throw new Exception('Missing model for rule: '. $rule['type']);
$ruleType = (!\is_null($rule['getNestedType'])) ? $rule['getNestedType']($item) : $rule['type'];
if (!array_key_exists($ruleType, $this->models)) {
throw new Exception('Missing model for rule: '. $ruleType);
}
$item = $this->output($item, $rule['type']);
$item = $this->output($item, $ruleType);
}
}
}

View file

@ -68,8 +68,14 @@ abstract class Model
/**
* Add a New Rule
* If rule is an array of documents with varying models
* Pass callable $getNestedType that accepts Document and returns the nested response type
*
* @param string $key
* @param array $options
* @param callable $getNestedType function(Document $value): string
*/
protected function addRule(string $key, array $options): self
protected function addRule(string $key, array $options, callable $getNestedType = null): self
{
$this->rules[$key] = array_merge([
'require' => true,
@ -78,6 +84,7 @@ abstract class Model
'default' => null,
'example' => '',
'array' => false,
'getNestedType' => $getNestedType
], $options);
return $this;