<?php
namespace Engine\Mvc\Response\Components; class Headers { private $headers = []; private $statusCode = 200; private $json = null; public function __construct($headers) { $this->headers = $headers; } public function setJson($json) :void { $this->json = $json; } public function getJson() :\stdClass { if ($this->json===null) { $this->json = new \stdClass(); } return $this->json; } public function setStatusCode(int $statusCode) :void { $this->statusCode = $statusCode; } public function getStatusCode() :int { return $this->statusCode; } public function getStatusName() :string { switch ($this->statusCode) { case '200': return 'OK'; break; case '404': return 'Not Found'; break; case '500': return 'Internal Server Error'; break; } return ''; } public function append($name, $value) :void { $this->headers[] = sprintf("%s: %s", $name, $value); } public function loadMessages(\App\MessagesCollector $msgs) :void { $jsonMessages = $this->getJson(); if (property_exists($jsonMessages, 'messages')) { $displayedMessages = (array)$jsonMessages->messages; } else { $displayedMessages = []; } foreach($msgs->getMessages() as $message) { $displayedMessages[] = ['type' => $message->getType(), 'message' => $message->getText()]; } $jsonMessages->messages = $displayedMessages; $this->setJson($jsonMessages); } public function getAll() :array { $headers = []; foreach ($this->headers as $header) { $headers[] = $header; } if ($this->json!==null && $this->json!=new \stdClass()) { $headers[] = sprintf("X-JSON: %s", json_encode((object)$this->json)); } return $headers; } } 