1
0
Fork 0
mirror of synced 2024-06-14 08:44:49 +12:00
appwrite/src/Appwrite/Utopia/Response.php

120 lines
2.9 KiB
PHP
Raw Normal View History

2020-05-16 23:28:26 +12:00
<?php
2020-06-23 00:17:14 +12:00
namespace Appwrite\Utopia;
2020-05-16 23:28:26 +12:00
use Exception;
2020-06-05 21:53:06 +12:00
use Appwrite\Database\Document;
2020-06-23 00:17:14 +12:00
use Appwrite\Utopia\Response\Result;
use Appwrite\Utopia\Response\Result\User;
2020-06-23 09:55:45 +12:00
use Appwrite\Utopia\Response\Result\Locale;
2020-05-16 23:28:26 +12:00
use Utopia\Response as UtopiaResponse;
class Response extends UtopiaResponse
{
2020-06-05 21:53:06 +12:00
public function __construct()
{
$this
2020-06-23 00:17:14 +12:00
->setResult(new User())
2020-06-23 09:55:45 +12:00
->setResult(new Locale())
2020-06-05 21:53:06 +12:00
;
}
2020-05-16 23:28:26 +12:00
/**
* HTTP content types
*/
const CONTENT_TYPE_YAML = 'application/x-yaml';
2020-06-05 21:53:06 +12:00
/**
* List of defined output objects
*/
protected $results = [];
/**
* Set Result Object
*
* @return self
*/
public function setResult(Result $result): self
2020-05-16 23:28:26 +12:00
{
2020-06-05 21:53:06 +12:00
$this->results[$result->getCollection()] = $result;
return $this;
}
/**
* Get Result Object
*
* @return Result
*/
public function getResult(string $key): Result
{
if(!isset($this->results[$key])) {
2020-06-23 00:17:14 +12:00
throw new Exception('Undefined result: '.$key);
2020-06-05 21:53:06 +12:00
}
return $this->results[$key];
}
/**
* Validate response objects and outputs
* the response according to given format type
*/
public function dynamic(Document $document, $type = self::CONTENT_TYPE_JSON)
{
$collection = $document->getCollection();
$data = $document->getArrayCopy();
$result = $this->getResult($collection);
$output = [];
foreach($result->getRules() as $key => $rule) {
if(!isset($data[$key])) {
2020-06-23 02:33:37 +12:00
if(!is_null($rule['default'])) {
$data[$key] = $rule['default'];
}
else {
throw new Exception('Missing response key: ' . $key);
}
2020-06-05 21:53:06 +12:00
}
$output[$key] = $data[$key];
}
switch ($type) {
case self::CONTENT_TYPE_JSON:
return $this->json($output);
break;
case self::CONTENT_TYPE_YAML:
return $this->yaml($output);
break;
default:
throw new Exception('Unknown content type');
break;
}
2020-05-16 23:28:26 +12:00
}
/**
* YAML
*
* This helper is for sending YAML HTTP response.
* It sets relevant content type header ('application/x-yaml') and convert a PHP array ($data) to valid YAML using native yaml_parse
*
* @see https://en.wikipedia.org/wiki/YAML
*
* @param array $data
*/
public function yaml(array $data)
{
if(!extension_loaded('yaml')) {
throw new Exception('Missing yaml extension. Learn more at: https://www.php.net/manual/en/book.yaml.php');
}
$this
->setContentType(Response::CONTENT_TYPE_YAML)
->send(yaml_emit($data, YAML_UTF8_ENCODING))
;
}
}