diff options
Diffstat (limited to 'private/View')
| -rw-r--r-- | private/View/Main.php | 26 | ||||
| -rw-r--r-- | private/View/Output.php | 34 |
2 files changed, 52 insertions, 8 deletions
diff --git a/private/View/Main.php b/private/View/Main.php index 1dcd760..746c2bb 100644 --- a/private/View/Main.php +++ b/private/View/Main.php @@ -18,6 +18,9 @@ class Main /** @var Model\Result $result the Result object to be sent to the client. */ private $result; + /** @var string TYPE The type of output the client should receive. */ + private const TYPE = "json"; + /** * Prepares the output and environment for the front end of the service. * @@ -27,8 +30,6 @@ class Main */ public function __construct (Model\Connection $connection) { - header("Content-Type: application/json"); - $this->query = Controller\Controller::createQuery( explode('/', trim($_SERVER['PATH_INFO'] ?? '/api', '/')), $_SERVER['REQUEST_METHOD'], @@ -58,7 +59,7 @@ class Main } /** - * Communicates with the controller to generate the JSON result. + * Communicates with the controller to generate the output. * * @return string */ @@ -69,10 +70,19 @@ class Main array() ); - // generate result - return json_encode(array( - "Result-Type" => $this->result->getResultType(), - "Content" => $this->result->getResult() - )); + return self::generateOutput($this->result); + } + + /** + * Creates output of the result based on the defined constant TYPE. + * + * @param Model\Result $result The result to be sent to the client. + * + * @return string + */ + public static function generateOutput (Model\Result $result): string + { + $type = self::TYPE; + return Output::$type($result); } } diff --git a/private/View/Output.php b/private/View/Output.php new file mode 100644 index 0000000..fe42c15 --- /dev/null +++ b/private/View/Output.php @@ -0,0 +1,34 @@ +<?php + +declare(strict_types=1); + +namespace AugustOffensive\View; + +use AugustOffensive\Model; + +/** + * Output formats for Results that are returned to the client. + */ +class Output +{ + /** + * Formats the result into JSON. + * + * @param Model\Result $result The result to return to the client. + * @param bool $prepare Whether to set the content type of the response (default true). + * + * @return string + */ + public static function json (Model\Result $result, bool $prepare = true): string + { + // breaks side effect rule? + if ($prepare) { + header("Content-Type: application/json"); + } + + return json_encode(array( + "Result-Type" => $result->getResultType(), + "Content" => $result->getResult() + )); + } +} |
