3 * @copyright Copyright (C) 2010-2022, 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;
46 public function setHeader(?string $header = null, ?string $key = null): void
48 if (!isset($header) && !empty($key)) {
49 unset($this->headers[$key]);
54 $this->headers[] = $header;
56 $this->headers[$key] = $header;
64 public function addContent($content): void
66 $this->content .= $content;
72 public function getHeaders(): array
74 return $this->headers;
80 public function getContent()
82 return $this->content;
88 public function setType(string $type, ?string $content_type = null): void
90 if (!in_array($type, static::ALLOWED_TYPES)) {
91 throw new InternalServerErrorException('wrong type');
95 case static::TYPE_JSON:
96 $content_type = $content_type ?? 'application/json';
98 case static::TYPE_XML:
99 $content_type = $content_type ?? 'text/xml';
101 case static::TYPE_RSS:
102 $content_type = $content_type ?? 'application/rss+xml';
104 case static::TYPE_ATOM:
105 $content_type = $content_type ?? 'application/atom+xml';
109 $this->setHeader($content_type, 'Content-type');
117 public function getType(): string
125 public function generate(): ResponseInterface
127 // Setting the response type as an X-header for direct usage
128 $this->headers[static::X_HEADER] = $this->type;
130 return new \GuzzleHttp\Psr7\Response(200, $this->headers, $this->content);