1
0
Fork 0
friendica_2020-09-1_sharedH.../src/Module/Response.php

114 lines
2 KiB
PHP
Raw Normal View History

<?php
namespace Friendica\Module;
2021-11-21 21:52:36 +01:00
use Friendica\Capabilities\ICanCreateResponses;
use Friendica\Network\HTTPException\InternalServerErrorException;
use Psr\Http\Message\ResponseInterface;
2021-11-21 21:52:36 +01:00
class Response implements ICanCreateResponses
{
/**
2021-11-21 21:52:36 +01:00
* @var string[]
*/
protected $headers = [];
/**
* @var string
*/
protected $content = '';
/**
* @var string
*/
2021-11-22 00:07:09 +01:00
protected $type = self::TYPE_HTML;
/**
* {@inheritDoc}
*/
2021-11-21 21:52:36 +01:00
public function setHeader(?string $header = null, ?string $key = null): void
{
2021-11-21 21:52:36 +01:00
if (!isset($header) && !empty($key)) {
unset($this->headers[$key]);
}
if (isset($header)) {
if (empty($key)) {
$this->headers[] = $header;
} else {
$this->headers[$key] = $header;
}
}
}
/**
* {@inheritDoc}
*/
2021-11-21 21:52:36 +01:00
public function addContent($content): void
{
$this->content .= $content;
}
/**
* {@inheritDoc}
*/
public function getHeaders(): array
{
return $this->headers;
}
/**
* {@inheritDoc}
*/
2021-11-21 21:52:36 +01:00
public function getContent()
{
return $this->content;
}
/**
* {@inheritDoc}
*/
2021-11-21 21:52:36 +01:00
public function setType(string $type, ?string $content_type = null): void
{
2021-11-22 00:07:09 +01:00
if (!in_array($type, static::ALLOWED_TYPES)) {
throw new InternalServerErrorException('wrong type');
}
2021-11-21 21:52:36 +01:00
switch ($type) {
case static::TYPE_JSON:
$content_type = $content_type ?? 'application/json';
break;
case static::TYPE_XML:
$content_type = $content_type ?? 'text/xml';
break;
2021-11-22 00:07:09 +01:00
case static::TYPE_RSS:
$content_type = $content_type ?? 'application/rss+xml';
break;
case static::TYPE_ATOM:
$content_type = $content_type ?? 'application/atom+xml';
break;
2021-11-21 21:52:36 +01:00
}
$this->setHeader($content_type, 'Content-type');
$this->type = $type;
}
/**
* {@inheritDoc}
*/
2021-11-21 21:52:36 +01:00
public function getType(): string
{
return $this->type;
}
/**
* {@inheritDoc}
*/
public function generate(): ResponseInterface
{
// Setting the response type as an X-header for direct usage
2021-11-22 00:07:09 +01:00
$this->headers[static::X_HEADER] = $this->type;
return new \GuzzleHttp\Psr7\Response(200, $this->headers, $this->content);
}
}