3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Module;
24 use Friendica\Capabilities\ICanCreateResponses;
25 use Friendica\Network\HTTPException\InternalServerErrorException;
26 use Psr\Http\Message\ResponseInterface;
28 class Response implements ICanCreateResponses
33 protected $headers = [];
37 protected $content = '';
41 protected $type = self::TYPE_HTML;
43 protected $status = 200;
45 protected $reason = null;
50 public function setHeader(?string $header = null, ?string $key = null): void
52 if (!isset($header) && !empty($key)) {
53 unset($this->headers[$key]);
58 $this->headers[] = $header;
60 $this->headers[$key] = $header;
68 public function addContent($content): void
70 $this->content .= $content;
76 public function getHeaders(): array
78 return $this->headers;
84 public function getContent()
86 return $this->content;
92 public function setType(string $type, ?string $content_type = null): void
94 if (!in_array($type, static::ALLOWED_TYPES)) {
95 throw new InternalServerErrorException('wrong type');
99 case static::TYPE_HTML:
100 $content_type = $content_type ?? 'text/html; charset=utf-8';
102 case static::TYPE_JSON:
103 $content_type = $content_type ?? 'application/json';
105 case static::TYPE_XML:
106 $content_type = $content_type ?? 'text/xml';
108 case static::TYPE_RSS:
109 $content_type = $content_type ?? 'application/rss+xml';
111 case static::TYPE_ATOM:
112 $content_type = $content_type ?? 'application/atom+xml';
116 $this->setHeader($content_type, 'Content-type');
124 public function setStatus(int $status = 200, ?string $reason = null): void
126 $this->status = $status;
127 $this->reason = $reason;
133 public function getType(): string
141 public function generate(): ResponseInterface
143 // Setting the response type as an X-header for direct usage
144 $this->headers[static::X_HEADER] = $this->type;
146 return new \GuzzleHttp\Psr7\Response($this->status, $this->headers, $this->content, '1.1', $this->reason);