Inherit ApiResponse from Response

This commit is contained in:
Philipp Holzer 2021-11-21 21:52:36 +01:00
parent 561aba18e3
commit 537b74f307
Signed by: nupplaPhil
GPG key ID: 24A7501396EB5432
46 changed files with 326 additions and 277 deletions

View file

@ -391,6 +391,7 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
return prepare_photo_data($type, false, $resource_id, $uid); return prepare_photo_data($type, false, $resource_id, $uid);
} else { } else {
throw new InternalServerErrorException("image upload failed"); throw new InternalServerErrorException("image upload failed");
DI::page()->exit(DI::apiResponse());
} }
} }

View file

@ -702,7 +702,11 @@ class App
// Let the module run it's internal process (init, get, post, ...) // Let the module run it's internal process (init, get, post, ...)
$response = $module->run($_POST, $_REQUEST); $response = $module->run($_POST, $_REQUEST);
if ($response->getType() === $response::TYPE_HTML) {
$page->run($this, $this->baseURL, $this->args, $this->mode, $response, $this->l10n, $this->profiler, $this->config, $pconfig); $page->run($this, $this->baseURL, $this->args, $this->mode, $response, $this->l10n, $this->profiler, $this->config, $pconfig);
} else {
$page->exit($response);
}
} catch (HTTPException $e) { } catch (HTTPException $e) {
(new ModuleHTTPException())->rawContent($e); (new ModuleHTTPException())->rawContent($e);
} }

View file

@ -371,6 +371,24 @@ class Page implements ArrayAccess
$this->footerScripts[] = trim($url, '/'); $this->footerScripts[] = trim($url, '/');
} }
/**
* Directly exit with the current response (include setting all headers)
*
* @param IRespondToRequests $response
*/
public function exit(IRespondToRequests $response)
{
foreach ($response->getHeaders() as $key => $header) {
if (empty($key)) {
header($header);
} else {
header("$key: $header");
}
}
echo $response->getContent();
}
/** /**
* Executes the creation of the current page and prints it to the screen * Executes the creation of the current page and prints it to the screen
* *
@ -434,13 +452,11 @@ class Page implements ArrayAccess
$this->page['nav'] = Nav::build($app); $this->page['nav'] = Nav::build($app);
} }
foreach ($response->getHeaders() as $key => $values) { foreach ($response->getHeaders() as $key => $header) {
if (is_array($values)) { if (empty($key)) {
foreach ($values as $value) { header($header);
header($key, $value);
}
} else { } else {
header($key, $values); header("$key: $header");
} }
} }

View file

@ -23,7 +23,7 @@ namespace Friendica;
use Friendica\App\Router; use Friendica\App\Router;
use Friendica\Capabilities\ICanHandleRequests; use Friendica\Capabilities\ICanHandleRequests;
use Friendica\Capabilities\ICanReadAndWriteToResponds; use Friendica\Capabilities\ICanCreateResponses;
use Friendica\Capabilities\IRespondToRequests; use Friendica\Capabilities\IRespondToRequests;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\L10n; use Friendica\Core\L10n;
@ -60,7 +60,7 @@ abstract class BaseModule implements ICanHandleRequests
protected $profiler; protected $profiler;
/** @var array */ /** @var array */
protected $server; protected $server;
/** @var ICanReadAndWriteToResponds */ /** @var ICanCreateResponses */
protected $response; protected $response;
public function __construct(L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = []) public function __construct(L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = [])
@ -168,12 +168,6 @@ abstract class BaseModule implements ICanHandleRequests
{ {
} }
/** Gets the name of the current class */
public function getClassName(): string
{
return static::class;
}
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@ -211,27 +205,23 @@ abstract class BaseModule implements ICanHandleRequests
Core\Hook::callAll($this->args->getModuleName() . '_mod_init', $placeholder); Core\Hook::callAll($this->args->getModuleName() . '_mod_init', $placeholder);
$this->profiler->set(microtime(true) - $timestamp, 'init'); $this->profiler->set(microtime(true) - $timestamp, 'init');
$this->response->setType(IRespondToRequests::TYPE_CONTENT);
switch ($this->server['REQUEST_METHOD']) { switch ($this->server['REQUEST_METHOD'] ?? Router::GET) {
case Router::DELETE: case Router::DELETE:
$this->response->setType(IRespondToRequests::TYPE_DELETE);
$this->delete(); $this->delete();
break; break;
case Router::PATCH: case Router::PATCH:
$this->response->setType(IRespondToRequests::TYPE_PATCH);
$this->patch(); $this->patch();
break; break;
case Router::POST: case Router::POST:
Core\Hook::callAll($this->args->getModuleName() . '_mod_post', $post); Core\Hook::callAll($this->args->getModuleName() . '_mod_post', $post);
$this->response->setType(IRespondToRequests::TYPE_POST);
$this->post($request, $post); $this->post($request, $post);
break; break;
case Router::PUT: case Router::PUT:
$this->response->setType(IRespondToRequests::TYPE_PUT);
$this->put(); $this->put();
break; break;
default: default:
$timestamp = microtime(true);
// "rawContent" is especially meant for technical endpoints. // "rawContent" is especially meant for technical endpoints.
// This endpoint doesn't need any theme initialization or other comparable stuff. // This endpoint doesn't need any theme initialization or other comparable stuff.
$this->rawContent($request); $this->rawContent($request);
@ -243,6 +233,8 @@ abstract class BaseModule implements ICanHandleRequests
$this->response->addContent($this->content($_REQUEST)); $this->response->addContent($this->content($_REQUEST));
} catch (HTTPException $e) { } catch (HTTPException $e) {
$this->response->addContent((new ModuleHTTPException())->content($e)); $this->response->addContent((new ModuleHTTPException())->content($e));
} finally {
$this->profiler->set(microtime(true) - $timestamp, 'content');
} }
break; break;
} }

View file

@ -0,0 +1,33 @@
<?php
namespace Friendica\Capabilities;
use Friendica\Network\HTTPException\InternalServerErrorException;
interface ICanCreateResponses extends IRespondToRequests
{
/**
* Adds a header entry to the module response
*
* @param string $header
* @param string|null $key
*/
public function setHeader(string $header, ?string $key = null): void;
/**
* Adds output content to the module response
*
* @param mixed $content
*/
public function addContent($content): void;
/**
* Sets the response type of the current request
*
* @param string $type
* @param string|null $content_type (optional) overrides the direct content_type, otherwise set the default one
*
* @throws InternalServerErrorException
*/
public function setType(string $type, ?string $content_type = null): void;
}

View file

@ -1,32 +0,0 @@
<?php
namespace Friendica\Capabilities;
use Friendica\Network\HTTPException\InternalServerErrorException;
interface ICanReadAndWriteToResponds extends IRespondToRequests
{
/**
* Adds a header entry to the module response
*
* @param string $key
* @param string $value
*/
public function addHeader(string $key, string $value);
/**
* Adds output content to the module response
*
* @param string $content
*/
public function addContent(string $content);
/**
* Sets the response type of the current request
*
* @param string $type
*
* @throws InternalServerErrorException
*/
public function setType(string $type);
}

View file

@ -4,40 +4,38 @@ namespace Friendica\Capabilities;
interface IRespondToRequests interface IRespondToRequests
{ {
const TYPE_CONTENT = 'content'; const TYPE_HTML = 'html';
const TYPE_RAW_CONTENT = 'rawContent'; const TYPE_XML = 'xml';
const TYPE_POST = 'post'; const TYPE_JSON = 'json';
const TYPE_PUT = 'put'; const TYPE_ATOM = 'atom';
const TYPE_DELETE = 'delete'; const TYPE_RSS = 'rss';
const TYPE_PATCH = 'patch';
const ALLOWED_TYPES = [ const ALLOWED_TYPES = [
self::TYPE_CONTENT, self::TYPE_HTML,
self::TYPE_RAW_CONTENT, self::TYPE_XML,
self::TYPE_POST, self::TYPE_JSON,
self::TYPE_PUT, self::TYPE_ATOM,
self::TYPE_DELETE, self::TYPE_RSS
self::TYPE_PATCH,
]; ];
/** /**
* Returns all set headers during the module execution * Returns all set headers during the module execution
* *
* @return string[][] * @return string[]
*/ */
public function getHeaders(): array; public function getHeaders(): array;
/** /**
* Returns the output of the module * Returns the output of the module (mixed content possible)
* *
* @return string * @return mixed
*/ */
public function getContent(): string; public function getContent();
/** /**
* Returns the response type of the current request * Returns the response type
* *
* @return string * @return string
*/ */
public function getTyp(): string; public function getType(): string;
} }

View file

@ -5,6 +5,7 @@ namespace Friendica\Module\Api;
use Friendica\App\Arguments; use Friendica\App\Arguments;
use Friendica\App\BaseURL; use Friendica\App\BaseURL;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Module\Response;
use Friendica\Util\Arrays; use Friendica\Util\Arrays;
use Friendica\Util\DateTimeFormat; use Friendica\Util\DateTimeFormat;
use Friendica\Util\HTTPInputData; use Friendica\Util\HTTPInputData;
@ -13,9 +14,9 @@ use Psr\Log\LoggerInterface;
use Friendica\Factory\Api\Twitter\User as TwitterUser; use Friendica\Factory\Api\Twitter\User as TwitterUser;
/** /**
* This class is used to format and return API responses * This class is used to format and create API responses
*/ */
class ApiResponse class ApiResponse extends Response
{ {
/** @var L10n */ /** @var L10n */
protected $l10n; protected $l10n;
@ -23,42 +24,18 @@ class ApiResponse
protected $args; protected $args;
/** @var LoggerInterface */ /** @var LoggerInterface */
protected $logger; protected $logger;
/** @var BaseURL */
protected $baseUrl;
/** @var TwitterUser */
protected $twitterUser;
/** public function __construct(L10n $l10n, Arguments $args, LoggerInterface $logger, BaseURL $baseUrl, TwitterUser $twitterUser)
* @param L10n $l10n
* @param Arguments $args
* @param LoggerInterface $logger
*/
public function __construct(L10n $l10n, Arguments $args, LoggerInterface $logger, BaseURL $baseurl, TwitterUser $twitteruser)
{ {
$this->l10n = $l10n; $this->l10n = $l10n;
$this->args = $args; $this->args = $args;
$this->logger = $logger; $this->logger = $logger;
$this->baseurl = $baseurl; $this->baseUrl = $baseUrl;
$this->twitterUser = $twitteruser; $this->twitterUser = $twitterUser;
}
/**
* Sets header directly
* mainly used to override it for tests
*
* @param string $header
*/
protected function setHeader(string $header)
{
header($header);
}
/**
* Prints output directly to the caller
* mainly used to override it for tests
*
* @param string $output
*/
protected function printOutput(string $output)
{
echo $output;
exit;
} }
/** /**
@ -125,12 +102,12 @@ class ApiResponse
$arr['$user'] = $user_info; $arr['$user'] = $user_info;
$arr['$rss'] = [ $arr['$rss'] = [
'alternate' => $user_info['url'], 'alternate' => $user_info['url'],
'self' => $this->baseurl . '/' . $this->args->getQueryString(), 'self' => $this->baseUrl . '/' . $this->args->getQueryString(),
'base' => $this->baseurl, 'base' => $this->baseUrl,
'updated' => DateTimeFormat::utc(null, DateTimeFormat::API), 'updated' => DateTimeFormat::utc(null, DateTimeFormat::API),
'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM), 'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
'language' => $user_info['lang'], 'language' => $user_info['lang'],
'logo' => $this->baseurl . '/images/friendica-32.png', 'logo' => $this->baseUrl . '/images/friendica-32.png',
]; ];
return $arr; return $arr;
@ -242,7 +219,7 @@ class ApiResponse
break; break;
} }
$this->printOutput($return); $this->addContent($return);
} }
/** /**

View file

@ -57,9 +57,9 @@ class Activity extends BaseApi
} else { } else {
$ok = 'ok'; $ok = 'ok';
} }
DI::apiResponse()->exit('ok', ['ok' => $ok], $this->parameters['extension'] ?? null); $this->response->exit('ok', ['ok' => $ok], $this->parameters['extension'] ?? null);
} else { } else {
DI::apiResponse()->error(500, 'Error adding activity', '', $this->parameters['extension'] ?? null); $this->response->error(500, 'Error adding activity', '', $this->parameters['extension'] ?? null);
} }
} }
} }

View file

@ -42,13 +42,15 @@ class Setseen extends BaseApi
// return error if id is zero // return error if id is zero
if (empty($request['id'])) { if (empty($request['id'])) {
$answer = ['result' => 'error', 'message' => 'message id not specified']; $answer = ['result' => 'error', 'message' => 'message id not specified'];
DI::apiResponse()->exit('direct_messages_setseen', ['$result' => $answer], $this->parameters['extension'] ?? null); $this->response->exit('direct_messages_setseen', ['$result' => $answer], $this->parameters['extension'] ?? null);
return;
} }
// error message if specified id is not in database // error message if specified id is not in database
if (!DBA::exists('mail', ['id' => $request['id'], 'uid' => $uid])) { if (!DBA::exists('mail', ['id' => $request['id'], 'uid' => $uid])) {
$answer = ['result' => 'error', 'message' => 'message id not in database']; $answer = ['result' => 'error', 'message' => 'message id not in database'];
DI::apiResponse()->exit('direct_messages_setseen', ['$result' => $answer], $this->parameters['extension'] ?? null); $this->response->exit('direct_messages_setseen', ['$result' => $answer], $this->parameters['extension'] ?? null);
return;
} }
// update seen indicator // update seen indicator
@ -58,6 +60,6 @@ class Setseen extends BaseApi
$answer = ['result' => 'error', 'message' => 'unknown error']; $answer = ['result' => 'error', 'message' => 'unknown error'];
} }
DI::apiResponse()->exit('direct_messages_setseen', ['$result' => $answer], $this->parameters['extension'] ?? null); $this->response->exit('direct_messages_setseen', ['$result' => $answer], $this->parameters['extension'] ?? null);
} }
} }

View file

@ -70,6 +70,6 @@ class Index extends BaseApi
]; ];
} }
DI::apiResponse()->exit('events', ['events' => $items], $this->parameters['extension'] ?? null); $this->response->exit('events', ['events' => $items], $this->parameters['extension'] ?? null);
} }
} }

View file

@ -70,7 +70,7 @@ class Delete extends BaseApi
if ($ret) { if ($ret) {
// return success // return success
$success = ['success' => $ret, 'gid' => $request['gid'], 'name' => $request['name'], 'status' => 'deleted', 'wrong users' => []]; $success = ['success' => $ret, 'gid' => $request['gid'], 'name' => $request['name'], 'status' => 'deleted', 'wrong users' => []];
DI::apiResponse()->exit('group_delete', ['$result' => $success], $parameters['extension'] ?? null); $this->response->exit('group_delete', ['$result' => $success], $parameters['extension'] ?? null);
} else { } else {
throw new BadRequestException('other API error'); throw new BadRequestException('other API error');
} }

View file

@ -56,6 +56,6 @@ class Notification extends BaseApi
$result = false; $result = false;
} }
DI::apiResponse()->exit('notes', ['note' => $result], $this->parameters['extension'] ?? null); $this->response->exit('notes', ['note' => $result], $this->parameters['extension'] ?? null);
} }
} }

View file

@ -64,7 +64,7 @@ class Delete extends BaseApi
Item::deleteForUser($condition, $uid); Item::deleteForUser($condition, $uid);
$result = ['result' => 'deleted', 'message' => 'photo with id `' . $request['photo_id'] . '` has been deleted from server.']; $result = ['result' => 'deleted', 'message' => 'photo with id `' . $request['photo_id'] . '` has been deleted from server.'];
DI::apiResponse()->exit('photo_delete', ['$result' => $result], $this->parameters['extension'] ?? null); $this->response->exit('photo_delete', ['$result' => $result], $this->parameters['extension'] ?? null);
} else { } else {
throw new InternalServerErrorException("unknown error on deleting photo from database table"); throw new InternalServerErrorException("unknown error on deleting photo from database table");
} }

View file

@ -67,7 +67,7 @@ class Delete extends BaseApi
// return success of deletion or error message // return success of deletion or error message
if ($result) { if ($result) {
$answer = ['result' => 'deleted', 'message' => 'album `' . $request['album'] . '` with all containing photos has been deleted.']; $answer = ['result' => 'deleted', 'message' => 'album `' . $request['album'] . '` with all containing photos has been deleted.'];
DI::apiResponse()->exit('photoalbum_delete', ['$result' => $answer], $this->parameters['extension'] ?? null); $this->response->exit('photoalbum_delete', ['$result' => $answer], $this->parameters['extension'] ?? null);
} else { } else {
throw new InternalServerErrorException("unknown error - deleting from database failed"); throw new InternalServerErrorException("unknown error - deleting from database failed");
} }

View file

@ -59,7 +59,7 @@ class Update extends BaseApi
// return success of updating or error message // return success of updating or error message
if ($result) { if ($result) {
$answer = ['result' => 'updated', 'message' => 'album `' . $request['album'] . '` with all containing photos has been renamed to `' . $request['album_new'] . '`.']; $answer = ['result' => 'updated', 'message' => 'album `' . $request['album'] . '` with all containing photos has been renamed to `' . $request['album_new'] . '`.'];
DI::apiResponse()->exit('photoalbum_update', ['$result' => $answer], $this->parameters['extension'] ?? null); $this->response->exit('photoalbum_update', ['$result' => $answer], $this->parameters['extension'] ?? null);
} else { } else {
throw new InternalServerErrorException("unknown error - updating in database failed"); throw new InternalServerErrorException("unknown error - updating in database failed");
} }

View file

@ -61,7 +61,7 @@ class Show extends BaseApi
'profiles' => $profiles 'profiles' => $profiles
]; ];
DI::apiResponse()->exit('friendica_profiles', ['$result' => $result], $this->parameters['extension'] ?? null); $this->response->exit('friendica_profiles', ['$result' => $result], $this->parameters['extension'] ?? null);
} }
/** /**

View file

@ -61,6 +61,6 @@ class Config extends BaseApi
], ],
]; ];
DI::apiResponse()->exit('config', ['config' => $config], $this->parameters['extension'] ?? null); $this->response->exit('config', ['config' => $config], $this->parameters['extension'] ?? null);
} }
} }

View file

@ -31,6 +31,6 @@ class Version extends BaseApi
{ {
protected function rawContent(array $request = []) protected function rawContent(array $request = [])
{ {
DI::apiResponse()->exit('version', ['version' => '0.9.7'], $this->parameters['extension'] ?? null); $this->response->exit('version', ['version' => '0.9.7'], $this->parameters['extension'] ?? null);
} }
} }

View file

@ -37,6 +37,6 @@ class Test extends BaseApi
$ok = 'ok'; $ok = 'ok';
} }
DI::apiResponse()->exit('ok', ['ok' => $ok], $this->parameters['extension'] ?? null); $this->response->exit('ok', ['ok' => $ok], $this->parameters['extension'] ?? null);
} }
} }

View file

@ -23,7 +23,6 @@ namespace Friendica\Module\Api\Mastodon\Accounts;
use Friendica\App\Router; use Friendica\App\Router;
use Friendica\Core\Logger; use Friendica\Core\Logger;
use Friendica\DI;
use Friendica\Module\BaseApi; use Friendica\Module\BaseApi;
use Friendica\Util\HTTPInputData; use Friendica\Util\HTTPInputData;
@ -41,6 +40,6 @@ class UpdateCredentials extends BaseApi
Logger::info('Patch data', ['data' => $data]); Logger::info('Patch data', ['data' => $data]);
DI::apiResponse()->unsupported(Router::PATCH); $this->response->unsupported(Router::PATCH);
} }
} }

View file

@ -35,7 +35,7 @@ class Filters extends BaseApi
{ {
self::checkAllowedScope(self::SCOPE_WRITE); self::checkAllowedScope(self::SCOPE_WRITE);
DI::apiResponse()->unsupported(Router::POST); $this->response->unsupported(Router::POST);
} }
/** /**

View file

@ -25,7 +25,6 @@ use Friendica\App\Router;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
use Friendica\Module\Api\ApiResponse;
use Friendica\Module\BaseApi; use Friendica\Module\BaseApi;
/** /**
@ -37,12 +36,12 @@ class Accounts extends BaseApi
{ {
protected function delete() protected function delete()
{ {
DI::apiResponse()->unsupported(Router::DELETE); $this->response->unsupported(Router::DELETE);
} }
protected function post(array $request = [], array $post = []) protected function post(array $request = [], array $post = [])
{ {
DI::apiResponse()->unsupported(Router::POST); $this->response->unsupported(Router::POST);
} }
/** /**

View file

@ -35,7 +35,7 @@ class Markers extends BaseApi
{ {
self::checkAllowedScope(self::SCOPE_WRITE); self::checkAllowedScope(self::SCOPE_WRITE);
DI::apiResponse()->unsupported(Router::POST); $this->response->unsupported(Router::POST);
} }
/** /**

View file

@ -26,7 +26,6 @@ use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
use Friendica\Model\Post; use Friendica\Model\Post;
use Friendica\Module\Api\ApiResponse;
use Friendica\Module\BaseApi; use Friendica\Module\BaseApi;
/** /**
@ -39,7 +38,7 @@ class ScheduledStatuses extends BaseApi
self::checkAllowedScope(self::SCOPE_WRITE); self::checkAllowedScope(self::SCOPE_WRITE);
$uid = self::getCurrentUserID(); $uid = self::getCurrentUserID();
DI::apiResponse()->unsupported(Router::PUT); $this->response->unsupported(Router::PUT);
} }
protected function delete() protected function delete()

View file

@ -22,7 +22,6 @@
namespace Friendica\Module\Api\Mastodon; namespace Friendica\Module\Api\Mastodon;
use Friendica\App\Router; use Friendica\App\Router;
use Friendica\DI;
use Friendica\Module\BaseApi; use Friendica\Module\BaseApi;
/** /**
@ -35,7 +34,7 @@ class Unimplemented extends BaseApi
*/ */
protected function delete() protected function delete()
{ {
DI::apiResponse()->unsupported(Router::DELETE); $this->response->unsupported(Router::DELETE);
} }
/** /**
@ -43,7 +42,7 @@ class Unimplemented extends BaseApi
*/ */
protected function patch() protected function patch()
{ {
DI::apiResponse()->unsupported(Router::PATCH); $this->response->unsupported(Router::PATCH);
} }
/** /**
@ -51,7 +50,7 @@ class Unimplemented extends BaseApi
*/ */
protected function post(array $request = [], array $post = []) protected function post(array $request = [], array $post = [])
{ {
DI::apiResponse()->unsupported(Router::POST); $this->response->unsupported(Router::POST);
} }
/** /**
@ -59,7 +58,7 @@ class Unimplemented extends BaseApi
*/ */
public function put() public function put()
{ {
DI::apiResponse()->unsupported(Router::PUT); $this->response->unsupported(Router::PUT);
} }
/** /**
@ -67,6 +66,6 @@ class Unimplemented extends BaseApi
*/ */
protected function rawContent(array $request = []) protected function rawContent(array $request = [])
{ {
DI::apiResponse()->unsupported(Router::GET); $this->response->unsupported(Router::GET);
} }
} }

View file

@ -22,7 +22,6 @@
namespace Friendica\Module\Api\Twitter\Account; namespace Friendica\Module\Api\Twitter\Account;
use Friendica\Module\BaseApi; use Friendica\Module\BaseApi;
use Friendica\DI;
use Friendica\Util\DateTimeFormat; use Friendica\Util\DateTimeFormat;
/** /**
@ -52,6 +51,6 @@ class RateLimitStatus extends BaseApi
]; ];
} }
DI::apiResponse()->exit('hash', ['hash' => $hash], $this->parameters['extension'] ?? null); $this->response->exit('hash', ['hash' => $hash], $this->parameters['extension'] ?? null);
} }
} }

View file

@ -27,9 +27,9 @@ use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
use Friendica\Model\Profile; use Friendica\Model\Profile;
use Friendica\Model\User; use Friendica\Model\User;
use Friendica\Module\Api\ApiResponse;
use Friendica\Module\BaseApi; use Friendica\Module\BaseApi;
use Friendica\Model\Contact; use Friendica\Model\Contact;
use Friendica\Module\Response;
use Friendica\Network\HTTPException; use Friendica\Network\HTTPException;
use Friendica\Util\Profiler; use Friendica\Util\Profiler;
use Friendica\Util\Strings; use Friendica\Util\Strings;
@ -40,9 +40,9 @@ abstract class ContactEndpoint extends BaseApi
const DEFAULT_COUNT = 20; const DEFAULT_COUNT = 20;
const MAX_COUNT = 200; const MAX_COUNT = 200;
public function __construct(L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = []) public function __construct(App $app, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, ApiResponse $response, array $server, array $parameters = [])
{ {
parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters); parent::__construct($app, $l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
self::checkAllowedScope(self::SCOPE_READ); self::checkAllowedScope(self::SCOPE_READ);
} }

View file

@ -22,7 +22,6 @@
namespace Friendica\Module\Api\Twitter; namespace Friendica\Module\Api\Twitter;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI;
use Friendica\Module\BaseApi; use Friendica\Module\BaseApi;
/** /**
@ -45,6 +44,6 @@ class SavedSearches extends BaseApi
DBA::close($terms); DBA::close($terms);
DI::apiResponse()->exit('terms', ['terms' => $result], $this->parameters['extension'] ?? null); $this->response->exit('terms', ['terms' => $result], $this->parameters['extension'] ?? null);
} }
} }

View file

@ -21,18 +21,23 @@
namespace Friendica\Module; namespace Friendica\Module;
use Friendica\App;
use Friendica\BaseModule; use Friendica\BaseModule;
use Friendica\Core\L10n;
use Friendica\Core\Logger; use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\DI; use Friendica\DI;
use Friendica\Model\Contact; use Friendica\Model\Contact;
use Friendica\Model\Post; use Friendica\Model\Post;
use Friendica\Model\User; use Friendica\Model\User;
use Friendica\Module\Api\ApiResponse;
use Friendica\Network\HTTPException; use Friendica\Network\HTTPException;
use Friendica\Security\BasicAuth; use Friendica\Security\BasicAuth;
use Friendica\Security\OAuth; use Friendica\Security\OAuth;
use Friendica\Util\DateTimeFormat; use Friendica\Util\DateTimeFormat;
use Friendica\Util\HTTPInputData; use Friendica\Util\HTTPInputData;
use Friendica\Util\Profiler;
use Psr\Log\LoggerInterface;
class BaseApi extends BaseModule class BaseApi extends BaseModule
{ {
@ -53,12 +58,23 @@ class BaseApi extends BaseModule
*/ */
protected static $request = []; protected static $request = [];
/** @var App */
protected $app;
/** @var ApiResponse */
protected $response;
public function __construct(App $app, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, ApiResponse $response, array $server, array $parameters = [])
{
parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
}
protected function delete() protected function delete()
{ {
self::checkAllowedScope(self::SCOPE_WRITE); self::checkAllowedScope(self::SCOPE_WRITE);
if (!DI::app()->isLoggedIn()) { if (!$this->app->isLoggedIn()) {
throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.')); throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
} }
} }
@ -66,8 +82,8 @@ class BaseApi extends BaseModule
{ {
self::checkAllowedScope(self::SCOPE_WRITE); self::checkAllowedScope(self::SCOPE_WRITE);
if (!DI::app()->isLoggedIn()) { if (!$this->app->isLoggedIn()) {
throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.')); throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
} }
} }
@ -75,8 +91,8 @@ class BaseApi extends BaseModule
{ {
self::checkAllowedScope(self::SCOPE_WRITE); self::checkAllowedScope(self::SCOPE_WRITE);
if (!DI::app()->isLoggedIn()) { if (!$this->app->isLoggedIn()) {
throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.')); throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
} }
} }
@ -84,8 +100,8 @@ class BaseApi extends BaseModule
{ {
self::checkAllowedScope(self::SCOPE_WRITE); self::checkAllowedScope(self::SCOPE_WRITE);
if (!DI::app()->isLoggedIn()) { if (!$this->app->isLoggedIn()) {
throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.')); throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
} }
} }

View file

@ -22,6 +22,7 @@
namespace Friendica\Module\HTTPException; namespace Friendica\Module\HTTPException;
use Friendica\BaseModule; use Friendica\BaseModule;
use Friendica\Capabilities\IRespondToRequests;
use Friendica\DI; use Friendica\DI;
use Friendica\Network\HTTPException; use Friendica\Network\HTTPException;
@ -32,7 +33,7 @@ class PageNotFound extends BaseModule
throw new HTTPException\NotFoundException(DI::l10n()->t('Page not found.')); throw new HTTPException\NotFoundException(DI::l10n()->t('Page not found.'));
} }
public function run(array $post = [], array $request = []): string public function run(array $post = [], array $request = []): IRespondToRequests
{ {
/* The URL provided does not resolve to a valid module. /* The URL provided does not resolve to a valid module.
* *

View file

@ -21,11 +21,15 @@
namespace Friendica\Module; namespace Friendica\Module;
use Friendica\App;
use Friendica\BaseModule; use Friendica\BaseModule;
use Friendica\Capabilities\IRespondToRequests;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\System; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\DI; use Friendica\Core\L10n;
use Friendica\Model\Nodeinfo; use Friendica\Model\Nodeinfo;
use Friendica\Util\Profiler;
use Psr\Log\LoggerInterface;
/** /**
* Version 1.0 of Nodeinfo, a standardized way of exposing metadata about a server running one of the distributed social networks. * Version 1.0 of Nodeinfo, a standardized way of exposing metadata about a server running one of the distributed social networks.
@ -33,10 +37,18 @@ use Friendica\Model\Nodeinfo;
*/ */
class NodeInfo110 extends BaseModule class NodeInfo110 extends BaseModule
{ {
/** @var IManageConfigValues */
protected $config;
public function __construct(L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, IManageConfigValues $config, array $server, array $parameters = [])
{
parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
$this->config = $config;
}
protected function rawContent(array $request = []) protected function rawContent(array $request = [])
{ {
$config = DI::config();
$nodeinfo = [ $nodeinfo = [
'version' => '1.0', 'version' => '1.0',
'software' => [ 'software' => [
@ -53,18 +65,18 @@ class NodeInfo110 extends BaseModule
], ],
'services' => [], 'services' => [],
'usage' => [], 'usage' => [],
'openRegistrations' => intval($config->get('config', 'register_policy')) !== Register::CLOSED, 'openRegistrations' => intval($this->config->get('config', 'register_policy')) !== Register::CLOSED,
'metadata' => [ 'metadata' => [
'nodeName' => $config->get('config', 'sitename'), 'nodeName' => $this->config->get('config', 'sitename'),
], ],
]; ];
if (!empty($config->get('system', 'diaspora_enabled'))) { if (!empty($this->config->get('system', 'diaspora_enabled'))) {
$nodeinfo['protocols']['inbound'][] = 'diaspora'; $nodeinfo['protocols']['inbound'][] = 'diaspora';
$nodeinfo['protocols']['outbound'][] = 'diaspora'; $nodeinfo['protocols']['outbound'][] = 'diaspora';
} }
if (empty($config->get('system', 'ostatus_disabled'))) { if (empty($this->config->get('system', 'ostatus_disabled'))) {
$nodeinfo['protocols']['inbound'][] = 'gnusocial'; $nodeinfo['protocols']['inbound'][] = 'gnusocial';
$nodeinfo['protocols']['outbound'][] = 'gnusocial'; $nodeinfo['protocols']['outbound'][] = 'gnusocial';
} }
@ -84,8 +96,9 @@ class NodeInfo110 extends BaseModule
$nodeinfo['metadata']['services']['inbound'][] = 'twitter'; $nodeinfo['metadata']['services']['inbound'][] = 'twitter';
} }
$nodeinfo['metadata']['explicitContent'] = $config->get('system', 'explicit_content', false) == true; $nodeinfo['metadata']['explicitContent'] = $this->config->get('system', 'explicit_content', false) == true;
System::jsonExit($nodeinfo, 'application/json; charset=utf-8', JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); $this->response->setType(IRespondToRequests::TYPE_JSON);
$this->response->addContent(json_encode($nodeinfo, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
} }
} }

View file

@ -21,11 +21,15 @@
namespace Friendica\Module; namespace Friendica\Module;
use Friendica\App;
use Friendica\BaseModule; use Friendica\BaseModule;
use Friendica\Capabilities\IRespondToRequests;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\System; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\DI; use Friendica\Core\L10n;
use Friendica\Model\Nodeinfo; use Friendica\Model\Nodeinfo;
use Friendica\Util\Profiler;
use Psr\Log\LoggerInterface;
/** /**
* Version 2.0 of Nodeinfo, a standardized way of exposing metadata about a server running one of the distributed social networks. * Version 2.0 of Nodeinfo, a standardized way of exposing metadata about a server running one of the distributed social networks.
@ -33,10 +37,18 @@ use Friendica\Model\Nodeinfo;
*/ */
class NodeInfo120 extends BaseModule class NodeInfo120 extends BaseModule
{ {
/** @var IManageConfigValues */
protected $config;
public function __construct(L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, IManageConfigValues $config, array $server, array $parameters = [])
{
parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
$this->config = $config;
}
protected function rawContent(array $request = []) protected function rawContent(array $request = [])
{ {
$config = DI::config();
$nodeinfo = [ $nodeinfo = [
'version' => '2.0', 'version' => '2.0',
'software' => [ 'software' => [
@ -46,17 +58,17 @@ class NodeInfo120 extends BaseModule
'protocols' => ['dfrn', 'activitypub'], 'protocols' => ['dfrn', 'activitypub'],
'services' => [], 'services' => [],
'usage' => [], 'usage' => [],
'openRegistrations' => intval($config->get('config', 'register_policy')) !== Register::CLOSED, 'openRegistrations' => intval($this->config->get('config', 'register_policy')) !== Register::CLOSED,
'metadata' => [ 'metadata' => [
'nodeName' => $config->get('config', 'sitename'), 'nodeName' => $this->config->get('config', 'sitename'),
], ],
]; ];
if (!empty($config->get('system', 'diaspora_enabled'))) { if (!empty($this->config->get('system', 'diaspora_enabled'))) {
$nodeinfo['protocols'][] = 'diaspora'; $nodeinfo['protocols'][] = 'diaspora';
} }
if (empty($config->get('system', 'ostatus_disabled'))) { if (empty($this->config->get('system', 'ostatus_disabled'))) {
$nodeinfo['protocols'][] = 'ostatus'; $nodeinfo['protocols'][] = 'ostatus';
} }
@ -72,12 +84,13 @@ class NodeInfo120 extends BaseModule
$nodeinfo['services']['inbound'][] = 'rss2.0'; $nodeinfo['services']['inbound'][] = 'rss2.0';
$nodeinfo['services']['outbound'][] = 'atom1.0'; $nodeinfo['services']['outbound'][] = 'atom1.0';
if (function_exists('imap_open') && !$config->get('system', 'imap_disabled')) { if (function_exists('imap_open') && !$this->config->get('system', 'imap_disabled')) {
$nodeinfo['services']['inbound'][] = 'imap'; $nodeinfo['services']['inbound'][] = 'imap';
} }
$nodeinfo['metadata']['explicitContent'] = $config->get('system', 'explicit_content', false) == true; $nodeinfo['metadata']['explicitContent'] = $this->config->get('system', 'explicit_content', false) == true;
System::jsonExit($nodeinfo, 'application/json; charset=utf-8', JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); $this->response->setType(IRespondToRequests::TYPE_JSON, 'application/json; charset=utf-8');
$this->response->addContent(json_encode($nodeinfo, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
} }
} }

View file

@ -21,11 +21,15 @@
namespace Friendica\Module; namespace Friendica\Module;
use Friendica\App;
use Friendica\BaseModule; use Friendica\BaseModule;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\L10n;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\DI;
use Friendica\Model\Nodeinfo; use Friendica\Model\Nodeinfo;
use Friendica\Util\Profiler;
use Psr\Log\LoggerInterface;
/** /**
* Version 1.0 of Nodeinfo 2, a sStandardized way of exposing metadata about a server running one of the distributed social networks. * Version 1.0 of Nodeinfo 2, a sStandardized way of exposing metadata about a server running one of the distributed social networks.
@ -33,30 +37,38 @@ use Friendica\Model\Nodeinfo;
*/ */
class NodeInfo210 extends BaseModule class NodeInfo210 extends BaseModule
{ {
/** @var IManageConfigValues */
protected $config;
public function __construct(L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, IManageConfigValues $config, array $server, array $parameters = [])
{
parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
$this->config = $config;
}
protected function rawContent(array $request = []) protected function rawContent(array $request = [])
{ {
$config = DI::config();
$nodeinfo = [ $nodeinfo = [
'version' => '1.0', 'version' => '1.0',
'server' => [ 'server' => [
'baseUrl' => DI::baseUrl()->get(), 'baseUrl' => $this->baseUrl->get(),
'name' => $config->get('config', 'sitename'), 'name' => $this->config->get('config', 'sitename'),
'software' => 'friendica', 'software' => 'friendica',
'version' => FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION, 'version' => FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
], ],
'organization' => Nodeinfo::getOrganization($config), 'organization' => Nodeinfo::getOrganization($this->config),
'protocols' => ['dfrn', 'activitypub'], 'protocols' => ['dfrn', 'activitypub'],
'services' => [], 'services' => [],
'openRegistrations' => intval($config->get('config', 'register_policy')) !== Register::CLOSED, 'openRegistrations' => intval($this->config->get('config', 'register_policy')) !== Register::CLOSED,
'usage' => [], 'usage' => [],
]; ];
if (!empty($config->get('system', 'diaspora_enabled'))) { if (!empty($this->config->get('system', 'diaspora_enabled'))) {
$nodeinfo['protocols'][] = 'diaspora'; $nodeinfo['protocols'][] = 'diaspora';
} }
if (empty($config->get('system', 'ostatus_disabled'))) { if (empty($this->config->get('system', 'ostatus_disabled'))) {
$nodeinfo['protocols'][] = 'ostatus'; $nodeinfo['protocols'][] = 'ostatus';
} }
@ -72,7 +84,7 @@ class NodeInfo210 extends BaseModule
$nodeinfo['services']['inbound'][] = 'rss2.0'; $nodeinfo['services']['inbound'][] = 'rss2.0';
$nodeinfo['services']['outbound'][] = 'atom1.0'; $nodeinfo['services']['outbound'][] = 'atom1.0';
if (function_exists('imap_open') && !$config->get('system', 'imap_disabled')) { if (function_exists('imap_open') && !$this->config->get('system', 'imap_disabled')) {
$nodeinfo['services']['inbound'][] = 'imap'; $nodeinfo['services']['inbound'][] = 'imap';
} }

View file

@ -2,14 +2,14 @@
namespace Friendica\Module; namespace Friendica\Module;
use Friendica\Capabilities\ICanReadAndWriteToResponds; use Friendica\Capabilities\ICanCreateResponses;
use Friendica\Capabilities\IRespondToRequests; use Friendica\Capabilities\IRespondToRequests;
use Friendica\Network\HTTPException\InternalServerErrorException; use Friendica\Network\HTTPException\InternalServerErrorException;
class Response implements ICanReadAndWriteToResponds class Response implements ICanCreateResponses
{ {
/** /**
* @var string[][] * @var string[]
*/ */
protected $headers = []; protected $headers = [];
/** /**
@ -19,20 +19,30 @@ class Response implements ICanReadAndWriteToResponds
/** /**
* @var string * @var string
*/ */
protected $type = IRespondToRequests::TYPE_CONTENT; protected $type = IRespondToRequests::TYPE_HTML;
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function addHeader(string $key, string $value) public function setHeader(?string $header = null, ?string $key = null): void
{ {
$this->headers[$key][] = $value; if (!isset($header) && !empty($key)) {
unset($this->headers[$key]);
}
if (isset($header)) {
if (empty($key)) {
$this->headers[] = $header;
} else {
$this->headers[$key] = $header;
}
}
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function addContent(string $content) public function addContent($content): void
{ {
$this->content .= $content; $this->content .= $content;
} }
@ -48,7 +58,7 @@ class Response implements ICanReadAndWriteToResponds
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function getContent(): string public function getContent()
{ {
return $this->content; return $this->content;
} }
@ -56,19 +66,31 @@ class Response implements ICanReadAndWriteToResponds
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function setType(string $type) public function setType(string $type, ?string $content_type = null): void
{ {
if (!in_array($type, IRespondToRequests::ALLOWED_TYPES)) { if (!in_array($type, IRespondToRequests::ALLOWED_TYPES)) {
throw new InternalServerErrorException('wrong type'); throw new InternalServerErrorException('wrong type');
} }
switch ($type) {
case static::TYPE_JSON:
$content_type = $content_type ?? 'application/json';
break;
case static::TYPE_XML:
$content_type = $content_type ?? 'text/xml';
break;
}
$this->setHeader($content_type, 'Content-type');
$this->type = $type; $this->type = $type;
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function getTyp(): string public function getType(): string
{ {
return $this->type; return $this->type;
} }

View file

@ -28,7 +28,7 @@ class ApiResponseDouble extends ApiResponse
/** /**
* The header list * The header list
* *
* @var string[] * @var string[][]
*/ */
protected static $header = []; protected static $header = [];
@ -61,9 +61,22 @@ class ApiResponseDouble extends ApiResponse
self::$header = []; self::$header = [];
} }
protected function setHeader(string $header) /**
* {@inheritDoc}
*/
public function setHeader(?string $header = null, ?string $key = null): void
{ {
if (!isset($header) && !empty($key)) {
unset(static::$header[$key]);
}
if (isset($header)) {
if (empty($key)) {
static::$header[] = $header; static::$header[] = $header;
} else {
static::$header[$key] = $header;
}
}
} }
protected function printOutput(string $output) protected function printOutput(string $output)

View file

@ -6,19 +6,12 @@ use Friendica\App\Arguments;
use Friendica\App\BaseURL; use Friendica\App\BaseURL;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Factory\Api\Twitter\User; use Friendica\Factory\Api\Twitter\User;
use Friendica\Module\Api\ApiResponse;
use Friendica\Test\MockedTest; use Friendica\Test\MockedTest;
use Friendica\Test\Util\ApiResponseDouble;
use Psr\Log\NullLogger; use Psr\Log\NullLogger;
class ApiResponseTest extends MockedTest class ApiResponseTest extends MockedTest
{ {
protected function tearDown(): void
{
ApiResponseDouble::reset();
parent::tearDown();
}
public function testErrorWithJson() public function testErrorWithJson()
{ {
$l10n = \Mockery::mock(L10n::class); $l10n = \Mockery::mock(L10n::class);
@ -27,10 +20,10 @@ class ApiResponseTest extends MockedTest
$baseUrl = \Mockery::mock(BaseURL::class); $baseUrl = \Mockery::mock(BaseURL::class);
$twitterUser = \Mockery::mock(User::class); $twitterUser = \Mockery::mock(User::class);
$response = new ApiResponseDouble($l10n, $args, new NullLogger(), $baseUrl, $twitterUser); $response = new ApiResponse($l10n, $args, new NullLogger(), $baseUrl, $twitterUser);
$response->error(200, 'OK', 'error_message', 'json'); $response->error(200, 'OK', 'error_message', 'json');
self::assertEquals('{"error":"error_message","code":"200 OK","request":""}', ApiResponseDouble::getOutput()); self::assertEquals('{"error":"error_message","code":"200 OK","request":""}', $response->getContent());
} }
public function testErrorWithXml() public function testErrorWithXml()
@ -41,7 +34,7 @@ class ApiResponseTest extends MockedTest
$baseUrl = \Mockery::mock(BaseURL::class); $baseUrl = \Mockery::mock(BaseURL::class);
$twitterUser = \Mockery::mock(User::class); $twitterUser = \Mockery::mock(User::class);
$response = new ApiResponseDouble($l10n, $args, new NullLogger(), $baseUrl, $twitterUser); $response = new ApiResponse($l10n, $args, new NullLogger(), $baseUrl, $twitterUser);
$response->error(200, 'OK', 'error_message', 'xml'); $response->error(200, 'OK', 'error_message', 'xml');
self::assertEquals('<?xml version="1.0"?>' . "\n" . self::assertEquals('<?xml version="1.0"?>' . "\n" .
@ -52,7 +45,7 @@ class ApiResponseTest extends MockedTest
' <code>200 OK</code>' . "\n" . ' <code>200 OK</code>' . "\n" .
' <request/>' . "\n" . ' <request/>' . "\n" .
'</status>' . "\n", '</status>' . "\n",
ApiResponseDouble::getOutput()); $response->getContent());
} }
public function testErrorWithRss() public function testErrorWithRss()
@ -63,7 +56,7 @@ class ApiResponseTest extends MockedTest
$baseUrl = \Mockery::mock(BaseURL::class); $baseUrl = \Mockery::mock(BaseURL::class);
$twitterUser = \Mockery::mock(User::class); $twitterUser = \Mockery::mock(User::class);
$response = new ApiResponseDouble($l10n, $args, new NullLogger(), $baseUrl, $twitterUser); $response = new ApiResponse($l10n, $args, new NullLogger(), $baseUrl, $twitterUser);
$response->error(200, 'OK', 'error_message', 'rss'); $response->error(200, 'OK', 'error_message', 'rss');
self::assertEquals( self::assertEquals(
@ -75,7 +68,7 @@ class ApiResponseTest extends MockedTest
' <code>200 OK</code>' . "\n" . ' <code>200 OK</code>' . "\n" .
' <request/>' . "\n" . ' <request/>' . "\n" .
'</status>' . "\n", '</status>' . "\n",
ApiResponseDouble::getOutput()); $response->getContent());
} }
public function testErrorWithAtom() public function testErrorWithAtom()
@ -86,7 +79,7 @@ class ApiResponseTest extends MockedTest
$baseUrl = \Mockery::mock(BaseURL::class); $baseUrl = \Mockery::mock(BaseURL::class);
$twitterUser = \Mockery::mock(User::class); $twitterUser = \Mockery::mock(User::class);
$response = new ApiResponseDouble($l10n, $args, new NullLogger(), $baseUrl, $twitterUser); $response = new ApiResponse($l10n, $args, new NullLogger(), $baseUrl, $twitterUser);
$response->error(200, 'OK', 'error_message', 'atom'); $response->error(200, 'OK', 'error_message', 'atom');
self::assertEquals( self::assertEquals(
@ -98,7 +91,7 @@ class ApiResponseTest extends MockedTest
' <code>200 OK</code>' . "\n" . ' <code>200 OK</code>' . "\n" .
' <request/>' . "\n" . ' <request/>' . "\n" .
'</status>' . "\n", '</status>' . "\n",
ApiResponseDouble::getOutput()); $response->getContent());
} }
public function testUnsupported() public function testUnsupported()
@ -112,9 +105,9 @@ class ApiResponseTest extends MockedTest
$baseUrl = \Mockery::mock(BaseURL::class); $baseUrl = \Mockery::mock(BaseURL::class);
$twitterUser = \Mockery::mock(User::class); $twitterUser = \Mockery::mock(User::class);
$response = new ApiResponseDouble($l10n, $args, new NullLogger(), $baseUrl, $twitterUser); $response = new ApiResponse($l10n, $args, new NullLogger(), $baseUrl, $twitterUser);
$response->unsupported(); $response->unsupported();
self::assertEquals('{"error":"API endpoint %s %s is not implemented","error_description":"The API endpoint is currently not implemented but might be in the future."}', ApiResponseDouble::getOutput()); self::assertEquals('{"error":"API endpoint %s %s is not implemented","error_description":"The API endpoint is currently not implemented but might be in the future."}', $response->getContent());
} }
} }

View file

@ -25,10 +25,8 @@ use Friendica\Core\Addon;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\DI; use Friendica\DI;
use Friendica\Module\Api\ApiResponse;
use Friendica\Security\Authentication; use Friendica\Security\Authentication;
use Friendica\Test\FixtureTest; use Friendica\Test\FixtureTest;
use Friendica\Test\Util\ApiResponseDouble;
use Friendica\Test\Util\AuthenticationDouble; use Friendica\Test\Util\AuthenticationDouble;
abstract class ApiTest extends FixtureTest abstract class ApiTest extends FixtureTest
@ -53,20 +51,12 @@ abstract class ApiTest extends FixtureTest
parent::setUp(); // TODO: Change the autogenerated stub parent::setUp(); // TODO: Change the autogenerated stub
$this->dice = $this->dice $this->dice = $this->dice
->addRule(Authentication::class, ['instanceOf' => AuthenticationDouble::class, 'shared' => true]) ->addRule(Authentication::class, ['instanceOf' => AuthenticationDouble::class, 'shared' => true]);
->addRule(ApiResponse::class, ['instanceOf' => ApiResponseDouble::class, 'shared' => true]);
DI::init($this->dice); DI::init($this->dice);
$this->installAuthTest(); $this->installAuthTest();
} }
protected function tearDown(): void
{
ApiResponseDouble::reset();
parent::tearDown();
}
/** /**
* installs auththest. * installs auththest.
* *

View file

@ -23,9 +23,7 @@ namespace Friendica\Test\src\Module\Api\Friendica;
use Friendica\DI; use Friendica\DI;
use Friendica\Module\Api\Friendica\Notification; use Friendica\Module\Api\Friendica\Notification;
use Friendica\Network\HTTPException\BadRequestException;
use Friendica\Test\src\Module\Api\ApiTest; use Friendica\Test\src\Module\Api\ApiTest;
use Friendica\Test\Util\ApiResponseDouble;
use Friendica\Util\DateTimeFormat; use Friendica\Util\DateTimeFormat;
use Friendica\Util\Temporal; use Friendica\Util\Temporal;
@ -67,19 +65,17 @@ class NotificationTest extends ApiTest
</notes> </notes>
XML; XML;
$notification = new Notification(DI::l10n(), ['extension' => 'xml']); $notification = new Notification(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), [], ['extension' => 'xml']);
$notification->rawContent(); $response = $notification->run();
self::assertXmlStringEqualsXmlString($assertXml, ApiResponseDouble::getOutput()); self::assertXmlStringEqualsXmlString($assertXml, $response->getContent());
} }
public function testWithJsonResult() public function testWithJsonResult()
{ {
$notification = new Notification(DI::l10n(),['parameter' => 'json']); $notification = new Notification(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), [], ['extension' => 'json']);
$notification->rawContent(); $response = $notification->run();
$result = json_encode(ApiResponseDouble::getOutput()); self::assertJson($response->getContent());
self::assertJson($result);
} }
} }

View file

@ -31,7 +31,7 @@ class DeleteTest extends ApiTest
public function testEmpty() public function testEmpty()
{ {
$this->expectException(BadRequestException::class); $this->expectException(BadRequestException::class);
(new Delete(DI::l10n()))->rawContent(); (new Delete(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), []))->run();
} }
public function testWithoutAuthenticatedUser() public function testWithoutAuthenticatedUser()
@ -42,7 +42,7 @@ class DeleteTest extends ApiTest
public function testWrong() public function testWrong()
{ {
$this->expectException(BadRequestException::class); $this->expectException(BadRequestException::class);
(new Delete(DI::l10n(), ['photo_id' => 1]))->rawContent(); (new Delete(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), []))->run(['photo_id' => 1]);
} }
public function testWithCorrectPhotoId() public function testWithCorrectPhotoId()

View file

@ -31,13 +31,14 @@ class DeleteTest extends ApiTest
public function testEmpty() public function testEmpty()
{ {
$this->expectException(BadRequestException::class); $this->expectException(BadRequestException::class);
(new Delete(DI::l10n()))->rawContent(); (new Delete(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), []))->run();
} }
public function testWrong() public function testWrong()
{ {
$this->expectException(BadRequestException::class); $this->expectException(BadRequestException::class);
(new Delete(DI::l10n(), ['album' => 'album_name']))->rawContent(); (new Delete(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), []))->run(['album' => 'album_name']);
} }
public function testValid() public function testValid()

View file

@ -31,19 +31,19 @@ class UpdateTest extends ApiTest
public function testEmpty() public function testEmpty()
{ {
$this->expectException(BadRequestException::class); $this->expectException(BadRequestException::class);
(new Update(DI::l10n()))->rawContent(); (new Update(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), []))->run();
} }
public function testTooFewArgs() public function testTooFewArgs()
{ {
$this->expectException(BadRequestException::class); $this->expectException(BadRequestException::class);
(new Update(DI::l10n(), ['album' => 'album_name']))->rawContent(); (new Update(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), []))->run(['album' => 'album_name']);
} }
public function testWrongUpdate() public function testWrongUpdate()
{ {
$this->expectException(BadRequestException::class); $this->expectException(BadRequestException::class);
(new Update(DI::l10n(), ['album' => 'album_name', 'album_new' => 'album_name']))->rawContent(); (new Update(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), []))->run(['album' => 'album_name', 'album_new' => 'album_name']);
} }
public function testWithoutAuthenticatedUser() public function testWithoutAuthenticatedUser()

View file

@ -5,17 +5,14 @@ namespace Friendica\Test\src\Module\Api\GnuSocial\GnuSocial;
use Friendica\DI; use Friendica\DI;
use Friendica\Module\Api\GNUSocial\GNUSocial\Version; use Friendica\Module\Api\GNUSocial\GNUSocial\Version;
use Friendica\Test\src\Module\Api\ApiTest; use Friendica\Test\src\Module\Api\ApiTest;
use Friendica\Test\Util\ApiResponseDouble;
class VersionTest extends ApiTest class VersionTest extends ApiTest
{ {
public function test() public function test()
{ {
$version = new Version(DI::l10n(), ['extension' => 'json']); $version = new Version(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), [], ['extension' => 'json']);
$version->rawContent(); $response = $version->run();
$result = json_decode(ApiResponseDouble::getOutput()); self::assertEquals('"0.9.7"', $response->getContent());
self::assertEquals('0.9.7', $result);
} }
} }

View file

@ -5,23 +5,22 @@ namespace Friendica\Test\src\Module\Api\GnuSocial\Help;
use Friendica\DI; use Friendica\DI;
use Friendica\Module\Api\GNUSocial\Help\Test; use Friendica\Module\Api\GNUSocial\Help\Test;
use Friendica\Test\src\Module\Api\ApiTest; use Friendica\Test\src\Module\Api\ApiTest;
use Friendica\Test\Util\ApiResponseDouble;
class TestTest extends ApiTest class TestTest extends ApiTest
{ {
public function testJson() public function testJson()
{ {
$test = new Test(DI::l10n(), ['extension' => 'json']); $test = new Test(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), [], ['extension' => 'json']);
$test->rawContent(); $response = $test->run();
self::assertEquals('"ok"', ApiResponseDouble::getOutput()); self::assertEquals('"ok"', $response->getContent());
} }
public function testXml() public function testXml()
{ {
$test = new Test(DI::l10n(), ['extension' => 'xml']); $test = new Test(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), [], ['extension' => 'xml']);
$test->rawContent(); $response = $test->run();
self::assertxml(ApiResponseDouble::getOutput(), 'ok'); self::assertxml($response->getContent(), 'ok');
} }
} }

View file

@ -5,16 +5,15 @@ namespace Friendica\Test\src\Module\Api\Twitter\Account;
use Friendica\DI; use Friendica\DI;
use Friendica\Module\Api\Twitter\Account\RateLimitStatus; use Friendica\Module\Api\Twitter\Account\RateLimitStatus;
use Friendica\Test\src\Module\Api\ApiTest; use Friendica\Test\src\Module\Api\ApiTest;
use Friendica\Test\Util\ApiResponseDouble;
class RateLimitStatusTest extends ApiTest class RateLimitStatusTest extends ApiTest
{ {
public function testWithJson() public function testWithJson()
{ {
$rateLimitStatus = new RateLimitStatus(DI::l10n(), ['extension' => 'json']); $rateLimitStatus = new RateLimitStatus(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), [], ['extension' => 'json']);
$rateLimitStatus->rawContent(); $response = $rateLimitStatus->run();
$result = json_decode(ApiResponseDouble::getOutput()); $result = json_decode($response->getContent());
self::assertEquals(150, $result->remaining_hits); self::assertEquals(150, $result->remaining_hits);
self::assertEquals(150, $result->hourly_limit); self::assertEquals(150, $result->hourly_limit);
@ -23,9 +22,9 @@ class RateLimitStatusTest extends ApiTest
public function testWithXml() public function testWithXml()
{ {
$rateLimitStatus = new RateLimitStatus(DI::l10n(),['extension' => 'xml']); $rateLimitStatus = new RateLimitStatus(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), [], ['extension' => 'xml']);
$rateLimitStatus->rawContent(); $response = $rateLimitStatus->run();
self::assertXml(ApiResponseDouble::getOutput(), 'hash'); self::assertXml($response->getContent(), 'hash');
} }
} }

View file

@ -5,16 +5,15 @@ namespace Friendica\Test\src\Module\Api\Twitter;
use Friendica\DI; use Friendica\DI;
use Friendica\Module\Api\Twitter\SavedSearches; use Friendica\Module\Api\Twitter\SavedSearches;
use Friendica\Test\src\Module\Api\ApiTest; use Friendica\Test\src\Module\Api\ApiTest;
use Friendica\Test\Util\ApiResponseDouble;
class SavedSearchesTest extends ApiTest class SavedSearchesTest extends ApiTest
{ {
public function test() public function test()
{ {
$savedSearch = new SavedSearches(DI::l10n(), ['extension' => 'json']); $savedSearch = new SavedSearches(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), [], ['extension' => 'json']);
$savedSearch->rawContent(); $response = $savedSearch->run();
$result = json_decode(ApiResponseDouble::getOutput()); $result = json_decode($response->getContent());
self::assertEquals(1, $result[0]->id); self::assertEquals(1, $result[0]->id);
self::assertEquals(1, $result[0]->id_str); self::assertEquals(1, $result[0]->id_str);