1
0
Fork 0
mirror of synced 2024-06-20 19:50:30 +12:00

Added team dynamic response

This commit is contained in:
Eldad Fux 2020-06-24 09:05:43 +03:00
parent dc2d990c29
commit dd2c6efbc9
5 changed files with 43 additions and 11 deletions

View file

@ -108,7 +108,10 @@ $utopia->get('/v1/teams')
],
]);
$response->json(['sum' => $projectDB->getSum(), 'teams' => $results]);
$response->dynamic(new Document([
'sum' => $projectDB->getSum(),
'teams' => $results
]), Response::MODEL_TEAM_LIST);
}
);

View file

@ -25,11 +25,11 @@ class Document extends ArrayObject
{
foreach ($input as $key => &$value) {
if (\is_array($value)) {
if (isset($value['$id']) || isset($value['$collection'])) {
if ((isset($value['$id']) || isset($value['$collection'])) && (!$value instanceof self)) {
$input[$key] = new self($value);
} else {
foreach ($value as $childKey => $child) {
if (isset($child['$id']) || isset($child['$collection'])) {
if ((isset($child['$id']) || isset($child['$collection'])) && (!$child instanceof self)) {
$value[$childKey] = new self($child);
}
}
@ -193,6 +193,18 @@ class Document extends ArrayObject
return empty($this->getId());
}
/**
* Checks if a document key is set.
*
* @param $key
*
* @return bool
*/
public function isSet($key)
{
return isset($this[$key]);
}
/**
* Get Array Copy.
*

View file

@ -101,28 +101,44 @@ class Response extends UtopiaResponse
*/
public function dynamic(Document $document, string $model)
{
$data = $document->getArrayCopy();
return $this->json($this->output($document, $model));
}
/**
* Generate valid response object from document data
*/
protected function output(Document $document, string $model): array
{
$data = $document;
$model = $this->getModel($model);
$output = [];
foreach($model->getRules() as $key => $rule) {
if(!isset($data[$key])) {
if(!$document->isSet($key)) {
if(!is_null($rule['default'])) {
$data[$key] = $rule['default'];
$document->setAttribute($key, $rule['default']);
}
else {
throw new Exception('Missing response key: '.$key);
}
}
if($rule['array'] && !is_array($data[$key])) {
throw new Exception($key.' must be an array of '.$rule['type'].' types');
if($rule['array']) {
if(!is_array($data[$key])) {
throw new Exception($key.' must be an array of '.$rule['type'].' types');
}
foreach ($data[$key] as &$item) {
if(array_key_exists($rule['type'], $this->models) && $item instanceof Document) {
$item = $this->output($item, $rule['type']);
}
}
}
$output[$key] = $data[$key];
}
return $this->json($output);
return $output;
}
/**

View file

@ -11,9 +11,9 @@ abstract class BaseList extends Model
{
$this
->addRule('sum', [
'type' => 'intgere',
'type' => 'integer',
'description' => 'Total sum of items in the list.',
'example' => '5e5ea5c16897e',
'example' => '5',
])
;
}

View file

@ -8,6 +8,7 @@ class TeamList extends BaseList
{
public function __construct()
{
parent::__construct();
$this
->addRule('teams', [
'type' => Response::MODEL_TEAM,