]> git.mxchange.org Git - friendica.git/commitdiff
Inherit `ApiResponse` from `Response`
authorPhilipp <admin@philipp.info>
Sun, 21 Nov 2021 20:52:36 +0000 (21:52 +0100)
committerPhilipp <admin@philipp.info>
Sat, 27 Nov 2021 11:40:54 +0000 (12:40 +0100)
46 files changed:
include/api.php
src/App.php
src/App/Page.php
src/BaseModule.php
src/Capabilities/ICanCreateResponses.php [new file with mode: 0644]
src/Capabilities/ICanReadAndWriteToResponds.php [deleted file]
src/Capabilities/IRespondToRequests.php
src/Module/Api/ApiResponse.php
src/Module/Api/Friendica/Activity.php
src/Module/Api/Friendica/DirectMessages/Setseen.php
src/Module/Api/Friendica/Events/Index.php
src/Module/Api/Friendica/Group/Delete.php
src/Module/Api/Friendica/Notification.php
src/Module/Api/Friendica/Photo/Delete.php
src/Module/Api/Friendica/Photoalbum/Delete.php
src/Module/Api/Friendica/Photoalbum/Update.php
src/Module/Api/Friendica/Profile/Show.php
src/Module/Api/GNUSocial/GNUSocial/Config.php
src/Module/Api/GNUSocial/GNUSocial/Version.php
src/Module/Api/GNUSocial/Help/Test.php
src/Module/Api/Mastodon/Accounts/UpdateCredentials.php
src/Module/Api/Mastodon/Filters.php
src/Module/Api/Mastodon/Lists/Accounts.php
src/Module/Api/Mastodon/Markers.php
src/Module/Api/Mastodon/ScheduledStatuses.php
src/Module/Api/Mastodon/Unimplemented.php
src/Module/Api/Twitter/Account/RateLimitStatus.php
src/Module/Api/Twitter/ContactEndpoint.php
src/Module/Api/Twitter/SavedSearches.php
src/Module/BaseApi.php
src/Module/HTTPException/PageNotFound.php
src/Module/NodeInfo110.php
src/Module/NodeInfo120.php
src/Module/NodeInfo210.php
src/Module/Response.php
tests/Util/ApiResponseDouble.php
tests/src/Module/Api/ApiResponseTest.php
tests/src/Module/Api/ApiTest.php
tests/src/Module/Api/Friendica/NotificationTest.php
tests/src/Module/Api/Friendica/Photo/DeleteTest.php
tests/src/Module/Api/Friendica/Photoalbum/DeleteTest.php
tests/src/Module/Api/Friendica/Photoalbum/UpdateTest.php
tests/src/Module/Api/GnuSocial/GnuSocial/VersionTest.php
tests/src/Module/Api/GnuSocial/Help/TestTest.php
tests/src/Module/Api/Twitter/Account/RateLimitStatusTest.php
tests/src/Module/Api/Twitter/SavedSearchesTest.php

index 9ed7d74218ae440d72a49f411f53bddf3a4c9a39..b291b6e0029cb1986a159e2bfac7dbc52a9ebc5f 100644 (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);
        } else {
                throw new InternalServerErrorException("image upload failed");
+               DI::page()->exit(DI::apiResponse());
        }
 }
 
index f3f7429db0651014ebe52aa4f6942024b81c7ddc..d4e3021f8253827c40ceea2272c97b555e1a6235 100644 (file)
@@ -702,7 +702,11 @@ class App
 
                        // Let the module run it's internal process (init, get, post, ...)
                        $response = $module->run($_POST, $_REQUEST);
-                       $page->run($this, $this->baseURL, $this->args, $this->mode, $response, $this->l10n, $this->profiler, $this->config, $pconfig);
+                       if ($response->getType() === $response::TYPE_HTML) {
+                               $page->run($this, $this->baseURL, $this->args, $this->mode, $response, $this->l10n, $this->profiler, $this->config, $pconfig);
+                       } else {
+                               $page->exit($response);
+                       }
                } catch (HTTPException $e) {
                        (new ModuleHTTPException())->rawContent($e);
                }
index 7996dca94fbba6b11a3e35e7fd4f8e94cc2eb5c5..7019d45985859d5e18dddbf534e470bf7cd027ec 100644 (file)
@@ -371,6 +371,24 @@ class Page implements ArrayAccess
                $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
         *
@@ -434,13 +452,11 @@ class Page implements ArrayAccess
                        $this->page['nav']      = Nav::build($app);
                }
 
-               foreach ($response->getHeaders() as $key => $values) {
-                       if (is_array($values)) {
-                               foreach ($values as $value) {
-                                       header($key, $value);
-                               }
+               foreach ($response->getHeaders() as $key => $header) {
+                       if (empty($key)) {
+                               header($header);
                        } else {
-                               header($key, $values);
+                               header("$key: $header");
                        }
                }
 
index c68af875d7aae46bb388c9928b7c4186359ce22b..423e11c7a5281e592fa2ea8875b71f60fed24874 100644 (file)
@@ -23,7 +23,7 @@ namespace Friendica;
 
 use Friendica\App\Router;
 use Friendica\Capabilities\ICanHandleRequests;
-use Friendica\Capabilities\ICanReadAndWriteToResponds;
+use Friendica\Capabilities\ICanCreateResponses;
 use Friendica\Capabilities\IRespondToRequests;
 use Friendica\Core\Hook;
 use Friendica\Core\L10n;
@@ -60,7 +60,7 @@ abstract class BaseModule implements ICanHandleRequests
        protected $profiler;
        /** @var array */
        protected $server;
-       /** @var ICanReadAndWriteToResponds */
+       /** @var ICanCreateResponses */
        protected $response;
 
        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}
         */
@@ -211,27 +205,23 @@ abstract class BaseModule implements ICanHandleRequests
                Core\Hook::callAll($this->args->getModuleName() . '_mod_init', $placeholder);
 
                $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:
-                               $this->response->setType(IRespondToRequests::TYPE_DELETE);
                                $this->delete();
                                break;
                        case Router::PATCH:
-                               $this->response->setType(IRespondToRequests::TYPE_PATCH);
                                $this->patch();
                                break;
                        case Router::POST:
                                Core\Hook::callAll($this->args->getModuleName() . '_mod_post', $post);
-                               $this->response->setType(IRespondToRequests::TYPE_POST);
                                $this->post($request, $post);
                                break;
                        case Router::PUT:
-                               $this->response->setType(IRespondToRequests::TYPE_PUT);
                                $this->put();
                                break;
                        default:
+                               $timestamp = microtime(true);
                                // "rawContent" is especially meant for technical endpoints.
                                // This endpoint doesn't need any theme initialization or other comparable stuff.
                                $this->rawContent($request);
@@ -243,6 +233,8 @@ abstract class BaseModule implements ICanHandleRequests
                                        $this->response->addContent($this->content($_REQUEST));
                                } catch (HTTPException $e) {
                                        $this->response->addContent((new ModuleHTTPException())->content($e));
+                               } finally {
+                                       $this->profiler->set(microtime(true) - $timestamp, 'content');
                                }
                                break;
                }
diff --git a/src/Capabilities/ICanCreateResponses.php b/src/Capabilities/ICanCreateResponses.php
new file mode 100644 (file)
index 0000000..2824581
--- /dev/null
@@ -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;
+}
diff --git a/src/Capabilities/ICanReadAndWriteToResponds.php b/src/Capabilities/ICanReadAndWriteToResponds.php
deleted file mode 100644 (file)
index 6b8ed5a..0000000
+++ /dev/null
@@ -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);
-}
index 974802fdef775717e9433b8b235266fe36bf8281..e023a9e4a15ef0b87b7a59046503a1a4f0c33035 100644 (file)
@@ -4,40 +4,38 @@ namespace Friendica\Capabilities;
 
 interface IRespondToRequests
 {
-       const TYPE_CONTENT     = 'content';
-       const TYPE_RAW_CONTENT = 'rawContent';
-       const TYPE_POST        = 'post';
-       const TYPE_PUT         = 'put';
-       const TYPE_DELETE      = 'delete';
-       const TYPE_PATCH       = 'patch';
+       const TYPE_HTML = 'html';
+       const TYPE_XML  = 'xml';
+       const TYPE_JSON = 'json';
+       const TYPE_ATOM = 'atom';
+       const TYPE_RSS  = 'rss';
 
        const ALLOWED_TYPES = [
-               self::TYPE_CONTENT,
-               self::TYPE_RAW_CONTENT,
-               self::TYPE_POST,
-               self::TYPE_PUT,
-               self::TYPE_DELETE,
-               self::TYPE_PATCH,
+               self::TYPE_HTML,
+               self::TYPE_XML,
+               self::TYPE_JSON,
+               self::TYPE_ATOM,
+               self::TYPE_RSS
        ];
 
        /**
         * Returns all set headers during the module execution
         *
-        * @return string[][]
+        * @return string[]
         */
        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
         */
-       public function getTyp(): string;
+       public function getType(): string;
 }
index 61886412a0f641c9ccff68a0a208c1b3f139cdd0..8a28e5766bec9459b5267d4733794b7eb97d75ed 100644 (file)
@@ -5,6 +5,7 @@ namespace Friendica\Module\Api;
 use Friendica\App\Arguments;
 use Friendica\App\BaseURL;
 use Friendica\Core\L10n;
+use Friendica\Module\Response;
 use Friendica\Util\Arrays;
 use Friendica\Util\DateTimeFormat;
 use Friendica\Util\HTTPInputData;
@@ -13,9 +14,9 @@ use Psr\Log\LoggerInterface;
 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 */
        protected $l10n;
@@ -23,42 +24,18 @@ class ApiResponse
        protected $args;
        /** @var LoggerInterface */
        protected $logger;
+       /** @var BaseURL */
+       protected $baseUrl;
+       /** @var TwitterUser */
+       protected $twitterUser;
 
-       /**
-        * @param L10n            $l10n
-        * @param Arguments       $args
-        * @param LoggerInterface $logger
-        */
-       public function __construct(L10n $l10n, Arguments $args, LoggerInterface $logger, BaseURL $baseurl, TwitterUser $twitteruser)
+       public function __construct(L10n $l10n, Arguments $args, LoggerInterface $logger, BaseURL $baseUrl, TwitterUser $twitterUser)
        {
                $this->l10n        = $l10n;
                $this->args        = $args;
                $this->logger      = $logger;
-               $this->baseurl     = $baseurl;
-               $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;
+               $this->baseUrl     = $baseUrl;
+               $this->twitterUser = $twitterUser;
        }
 
        /**
@@ -125,12 +102,12 @@ class ApiResponse
                $arr['$user'] = $user_info;
                $arr['$rss'] = [
                        'alternate'    => $user_info['url'],
-                       'self'         => $this->baseurl . '/' . $this->args->getQueryString(),
-                       'base'         => $this->baseurl,
+                       'self'         => $this->baseUrl . '/' . $this->args->getQueryString(),
+                       'base'         => $this->baseUrl,
                        'updated'      => DateTimeFormat::utc(null, DateTimeFormat::API),
                        'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
                        'language'     => $user_info['lang'],
-                       'logo'         => $this->baseurl . '/images/friendica-32.png',
+                       'logo'         => $this->baseUrl . '/images/friendica-32.png',
                ];
 
                return $arr;
@@ -242,7 +219,7 @@ class ApiResponse
                                break;
                }
 
-               $this->printOutput($return);
+               $this->addContent($return);
        }
 
        /**
index c65d32d0e70839849f10340a34be1dbdeb3c5390..aaab6417fbdf05770800b6e6598d7aa8be1e0623 100644 (file)
@@ -57,9 +57,9 @@ class Activity extends BaseApi
                        } else {
                                $ok = 'ok';
                        }
-                       DI::apiResponse()->exit('ok', ['ok' => $ok], $this->parameters['extension'] ?? null);
+                       $this->response->exit('ok', ['ok' => $ok], $this->parameters['extension'] ?? null);
                } else {
-                       DI::apiResponse()->error(500, 'Error adding activity', '', $this->parameters['extension'] ?? null);
+                       $this->response->error(500, 'Error adding activity', '', $this->parameters['extension'] ?? null);
                }
        }
 }
index 6e1f3675fc1399b1a828641ff6d65c9b36a08955..d64b4ee15d035b2cde9a14bcf8c9e1f8bda37226 100644 (file)
@@ -42,13 +42,15 @@ class Setseen extends BaseApi
                // return error if id is zero
                if (empty($request['id'])) {
                        $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
                if (!DBA::exists('mail', ['id' => $request['id'], 'uid' => $uid])) {
                        $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
@@ -58,6 +60,6 @@ class Setseen extends BaseApi
                        $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);
        }
 }
index 177e26f52bab8dd0c637d99fd7e40d4b8bc36997..86f79578d11ca53ef55c1a422b7cbc0791c87580 100644 (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);
        }
 }
index 9583c003d7601cdcb1559fdc95fe69cbc41f44da..56b3445c0dfd250372462ddbab5bc3b1f0726498 100644 (file)
@@ -70,7 +70,7 @@ class Delete extends BaseApi
                if ($ret) {
                        // return success
                        $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 {
                        throw new BadRequestException('other API error');
                }
index 76bce7de27041af02138d8126d34cf526156dac7..597f3d681114386876ff55345162f5190308ebc9 100644 (file)
@@ -56,6 +56,6 @@ class Notification extends BaseApi
                        $result = false;
                }
 
-               DI::apiResponse()->exit('notes', ['note' => $result], $this->parameters['extension'] ?? null);
+               $this->response->exit('notes', ['note' => $result], $this->parameters['extension'] ?? null);
        }
 }
index 7da819a7a2748f29a31b1000af54030e5091ae58..2edf398aab49a8ea6152f8ac2c5db052f0d5ee99 100644 (file)
@@ -64,7 +64,7 @@ class Delete extends BaseApi
                        Item::deleteForUser($condition, $uid);
 
                        $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 {
                        throw new InternalServerErrorException("unknown error on deleting photo from database table");
                }
index a8bb5d45e9ebce4115d18447892215b208b22654..c7592a5eaf0c8eec8ec3de8c3824031171ed1bc7 100644 (file)
@@ -67,7 +67,7 @@ class Delete extends BaseApi
                // return success of deletion or error message
                if ($result) {
                        $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 {
                        throw new InternalServerErrorException("unknown error - deleting from database failed");
                }
index d4d601790972ce8630fe57467b7fc911d67e104f..87513c5ad4d7db5e890d6fe460d86aa6bf0d4b58 100644 (file)
@@ -59,7 +59,7 @@ class Update extends BaseApi
                // return success of updating or error message
                if ($result) {
                        $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 {
                        throw new InternalServerErrorException("unknown error - updating in database failed");
                }
index 27a19f48e5412e9e0a5e9b5bf66644baa338bedd..6e77f9731e847595ac0afd4acc903d221c2ac6be 100644 (file)
@@ -61,7 +61,7 @@ class Show extends BaseApi
                        'profiles' => $profiles
                ];
 
-               DI::apiResponse()->exit('friendica_profiles', ['$result' => $result], $this->parameters['extension'] ?? null);
+               $this->response->exit('friendica_profiles', ['$result' => $result], $this->parameters['extension'] ?? null);
        }
 
        /**
index a3556fcdd9fc7705aea1a7cd75366c3d72fc237a..094fd5a100491dd556560b1c77850c5beb370bfb 100644 (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);
        }
 }
index 67f23628c14f5c99f29d03019a9d7b8aed2453cc..9b2afe128e57f4086c43b6de21cdcf966cfb5c12 100644 (file)
@@ -31,6 +31,6 @@ class Version extends BaseApi
 {
        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);
        }
 }
index e2f05183e6a93cdeb51dd5a1a9ceaaa7abf250cb..0a2ef6f831d7f75549bb9d5c74c03029a3b51b63 100644 (file)
@@ -37,6 +37,6 @@ class Test extends BaseApi
                        $ok = 'ok';
                }
 
-               DI::apiResponse()->exit('ok', ['ok' => $ok], $this->parameters['extension'] ?? null);
+               $this->response->exit('ok', ['ok' => $ok], $this->parameters['extension'] ?? null);
        }
 }
index 1a390d4a1fae00ff04ac15899ec9d7b7bd02539c..8d9fb48695f1736631e2233ac7a24941e1058002 100644 (file)
@@ -23,7 +23,6 @@ namespace Friendica\Module\Api\Mastodon\Accounts;
 
 use Friendica\App\Router;
 use Friendica\Core\Logger;
-use Friendica\DI;
 use Friendica\Module\BaseApi;
 use Friendica\Util\HTTPInputData;
 
@@ -41,6 +40,6 @@ class UpdateCredentials extends BaseApi
 
                Logger::info('Patch data', ['data' => $data]);
 
-               DI::apiResponse()->unsupported(Router::PATCH);
+               $this->response->unsupported(Router::PATCH);
        }
 }
index 38fc27ebc00dd2f1aeb5a1563e42b64caa59e71e..3c902bc17b664c4c65bde857191c6bc9713f3106 100644 (file)
@@ -35,7 +35,7 @@ class Filters extends BaseApi
        {
                self::checkAllowedScope(self::SCOPE_WRITE);
 
-               DI::apiResponse()->unsupported(Router::POST);
+               $this->response->unsupported(Router::POST);
        }
 
        /**
index 66d6f068ec848e61e1b9451f8f10b3b557fb996d..be87dbf9d1a9ad40ebbb4ce5ee6c25f1e5e4622d 100644 (file)
@@ -25,7 +25,6 @@ use Friendica\App\Router;
 use Friendica\Core\System;
 use Friendica\Database\DBA;
 use Friendica\DI;
-use Friendica\Module\Api\ApiResponse;
 use Friendica\Module\BaseApi;
 
 /**
@@ -37,12 +36,12 @@ class Accounts extends BaseApi
 {
        protected function delete()
        {
-               DI::apiResponse()->unsupported(Router::DELETE);
+               $this->response->unsupported(Router::DELETE);
        }
 
        protected function post(array $request = [], array $post = [])
        {
-               DI::apiResponse()->unsupported(Router::POST);
+               $this->response->unsupported(Router::POST);
        }
 
        /**
index 5cd38925e46c6e14bd46cff4e40074e1ff653a19..9f208e92624a7d409d493b69f01d97d190619ae9 100644 (file)
@@ -35,7 +35,7 @@ class Markers extends BaseApi
        {
                self::checkAllowedScope(self::SCOPE_WRITE);
 
-               DI::apiResponse()->unsupported(Router::POST);
+               $this->response->unsupported(Router::POST);
        }
 
        /**
index 605aaeb6d6a06229978b550a919325acb33d95e3..e79d1e153fb722daed5e04b63894d85fb5fb10fd 100644 (file)
@@ -26,7 +26,6 @@ use Friendica\Core\System;
 use Friendica\Database\DBA;
 use Friendica\DI;
 use Friendica\Model\Post;
-use Friendica\Module\Api\ApiResponse;
 use Friendica\Module\BaseApi;
 
 /**
@@ -39,7 +38,7 @@ class ScheduledStatuses extends BaseApi
                self::checkAllowedScope(self::SCOPE_WRITE);
                $uid = self::getCurrentUserID();
 
-               DI::apiResponse()->unsupported(Router::PUT);
+               $this->response->unsupported(Router::PUT);
        }
 
        protected function delete()
index 9874b504a78484e89c23a51e0866f0689f2d0ad4..22111781bbafc9df25ba3272b999147c402ed1b5 100644 (file)
@@ -22,7 +22,6 @@
 namespace Friendica\Module\Api\Mastodon;
 
 use Friendica\App\Router;
-use Friendica\DI;
 use Friendica\Module\BaseApi;
 
 /**
@@ -35,7 +34,7 @@ class Unimplemented extends BaseApi
         */
        protected function delete()
        {
-               DI::apiResponse()->unsupported(Router::DELETE);
+               $this->response->unsupported(Router::DELETE);
        }
 
        /**
@@ -43,7 +42,7 @@ class Unimplemented extends BaseApi
         */
        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 = [])
        {
-               DI::apiResponse()->unsupported(Router::POST);
+               $this->response->unsupported(Router::POST);
        }
 
        /**
@@ -59,7 +58,7 @@ class Unimplemented extends BaseApi
         */
        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 = [])
        {
-               DI::apiResponse()->unsupported(Router::GET);
+               $this->response->unsupported(Router::GET);
        }
 }
index 82cf2c3e660c0195b6b3d98d6946ad6cbbe6685c..5f1d37e7b5eb72b7dfcd138cb0f18209ee25a0e6 100644 (file)
@@ -22,7 +22,6 @@
 namespace Friendica\Module\Api\Twitter\Account;
 
 use Friendica\Module\BaseApi;
-use Friendica\DI;
 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);
        }
 }
index 2b2936820def35eb5401fe7256541531fc9119df..541f7fd86d05e31040361a188d96bcb5cc0d05a2 100644 (file)
@@ -27,9 +27,9 @@ use Friendica\Database\DBA;
 use Friendica\DI;
 use Friendica\Model\Profile;
 use Friendica\Model\User;
+use Friendica\Module\Api\ApiResponse;
 use Friendica\Module\BaseApi;
 use Friendica\Model\Contact;
-use Friendica\Module\Response;
 use Friendica\Network\HTTPException;
 use Friendica\Util\Profiler;
 use Friendica\Util\Strings;
@@ -40,9 +40,9 @@ abstract class ContactEndpoint extends BaseApi
        const DEFAULT_COUNT = 20;
        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);
        }
index 3fd30e34ea93cceb9c9ed07166c51d005a65f091..31824a8d4c0a72be13dece18f943cec0577e9728 100644 (file)
@@ -22,7 +22,6 @@
 namespace Friendica\Module\Api\Twitter;
 
 use Friendica\Database\DBA;
-use Friendica\DI;
 use Friendica\Module\BaseApi;
 
 /**
@@ -45,6 +44,6 @@ class SavedSearches extends BaseApi
 
                DBA::close($terms);
 
-               DI::apiResponse()->exit('terms', ['terms' => $result], $this->parameters['extension'] ?? null);
+               $this->response->exit('terms', ['terms' => $result], $this->parameters['extension'] ?? null);
        }
 }
index 03a28951e3f8e575a5635cc4572d7ad013f1c634..009809376e189bfb9ac232adf30c94af68dab090 100644 (file)
 
 namespace Friendica\Module;
 
+use Friendica\App;
 use Friendica\BaseModule;
+use Friendica\Core\L10n;
 use Friendica\Core\Logger;
 use Friendica\Core\System;
 use Friendica\DI;
 use Friendica\Model\Contact;
 use Friendica\Model\Post;
 use Friendica\Model\User;
+use Friendica\Module\Api\ApiResponse;
 use Friendica\Network\HTTPException;
 use Friendica\Security\BasicAuth;
 use Friendica\Security\OAuth;
 use Friendica\Util\DateTimeFormat;
 use Friendica\Util\HTTPInputData;
+use Friendica\Util\Profiler;
+use Psr\Log\LoggerInterface;
 
 class BaseApi extends BaseModule
 {
@@ -53,12 +58,23 @@ class BaseApi extends BaseModule
         */
        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()
        {
                self::checkAllowedScope(self::SCOPE_WRITE);
 
-               if (!DI::app()->isLoggedIn()) {
-                       throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
+               if (!$this->app->isLoggedIn()) {
+                       throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
                }
        }
 
@@ -66,8 +82,8 @@ class BaseApi extends BaseModule
        {
                self::checkAllowedScope(self::SCOPE_WRITE);
 
-               if (!DI::app()->isLoggedIn()) {
-                       throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
+               if (!$this->app->isLoggedIn()) {
+                       throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
                }
        }
 
@@ -75,8 +91,8 @@ class BaseApi extends BaseModule
        {
                self::checkAllowedScope(self::SCOPE_WRITE);
 
-               if (!DI::app()->isLoggedIn()) {
-                       throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
+               if (!$this->app->isLoggedIn()) {
+                       throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
                }
        }
 
@@ -84,8 +100,8 @@ class BaseApi extends BaseModule
        {
                self::checkAllowedScope(self::SCOPE_WRITE);
 
-               if (!DI::app()->isLoggedIn()) {
-                       throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
+               if (!$this->app->isLoggedIn()) {
+                       throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
                }
        }
 
index 4971ed3cd0c41353704907c4c5dbc2228e472470..0ec357656f9a956810389444f86a717f82ec6a0d 100644 (file)
@@ -22,6 +22,7 @@
 namespace Friendica\Module\HTTPException;
 
 use Friendica\BaseModule;
+use Friendica\Capabilities\IRespondToRequests;
 use Friendica\DI;
 use Friendica\Network\HTTPException;
 
@@ -32,7 +33,7 @@ class PageNotFound extends BaseModule
                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.
                 *
index 9e5a4cac9741f5e2e5f6c5e782b83e415430009c..6681dcc020a3ac90ba953deda40e861672ede4de 100644 (file)
 
 namespace Friendica\Module;
 
+use Friendica\App;
 use Friendica\BaseModule;
+use Friendica\Capabilities\IRespondToRequests;
 use Friendica\Core\Addon;
-use Friendica\Core\System;
-use Friendica\DI;
+use Friendica\Core\Config\Capability\IManageConfigValues;
+use Friendica\Core\L10n;
 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.
@@ -33,10 +37,18 @@ use Friendica\Model\Nodeinfo;
  */
 class NodeInfo110 extends BaseModule
 {
-       protected function rawContent(array $request = [])
+       /** @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 = [])
        {
-               $config = DI::config();
+               parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
+
+               $this->config = $config;
+       }
 
+       protected function rawContent(array $request = [])
+       {
                $nodeinfo = [
                        'version'           => '1.0',
                        'software'          => [
@@ -53,19 +65,19 @@ class NodeInfo110 extends BaseModule
                        ],
                        'services'          => [],
                        'usage'             => [],
-                       'openRegistrations' => intval($config->get('config', 'register_policy')) !== Register::CLOSED,
+                       'openRegistrations' => intval($this->config->get('config', 'register_policy')) !== Register::CLOSED,
                        'metadata'          => [
-                               'nodeName' => $config->get('config', 'sitename'),
+                               'nodeName' => $this->config->get('config', 'sitename'),
                        ],
                ];
 
-               if (!empty($config->get('system', 'diaspora_enabled'))) {
-                       $nodeinfo['protocols']['inbound'][] = 'diaspora';
+               if (!empty($this->config->get('system', 'diaspora_enabled'))) {
+                       $nodeinfo['protocols']['inbound'][]  = 'diaspora';
                        $nodeinfo['protocols']['outbound'][] = 'diaspora';
                }
 
-               if (empty($config->get('system', 'ostatus_disabled'))) {
-                       $nodeinfo['protocols']['inbound'][] = 'gnusocial';
+               if (empty($this->config->get('system', 'ostatus_disabled'))) {
+                       $nodeinfo['protocols']['inbound'][]  = 'gnusocial';
                        $nodeinfo['protocols']['outbound'][] = 'gnusocial';
                }
 
@@ -73,10 +85,10 @@ class NodeInfo110 extends BaseModule
 
                $nodeinfo['services'] = Nodeinfo::getServices();
 
-               $nodeinfo['metadata']['protocols'] = $nodeinfo['protocols'];
+               $nodeinfo['metadata']['protocols']               = $nodeinfo['protocols'];
                $nodeinfo['metadata']['protocols']['outbound'][] = 'atom1.0';
-               $nodeinfo['metadata']['protocols']['inbound'][] = 'atom1.0';
-               $nodeinfo['metadata']['protocols']['inbound'][] = 'rss2.0';
+               $nodeinfo['metadata']['protocols']['inbound'][]  = 'atom1.0';
+               $nodeinfo['metadata']['protocols']['inbound'][]  = 'rss2.0';
 
                $nodeinfo['metadata']['services'] = $nodeinfo['services'];
 
@@ -84,8 +96,9 @@ class NodeInfo110 extends BaseModule
                        $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));
        }
 }
index b0d5b18c8c147ae0d291166a82914c526810310b..ea25653779effbb993a190c99ec6256efa4fd8d1 100644 (file)
 
 namespace Friendica\Module;
 
+use Friendica\App;
 use Friendica\BaseModule;
+use Friendica\Capabilities\IRespondToRequests;
 use Friendica\Core\Addon;
-use Friendica\Core\System;
-use Friendica\DI;
+use Friendica\Core\Config\Capability\IManageConfigValues;
+use Friendica\Core\L10n;
 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.
@@ -33,30 +37,38 @@ use Friendica\Model\Nodeinfo;
  */
 class NodeInfo120 extends BaseModule
 {
-       protected function rawContent(array $request = [])
+       /** @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 = [])
        {
-               $config = DI::config();
+               parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
+
+               $this->config = $config;
+       }
 
+       protected function rawContent(array $request = [])
+       {
                $nodeinfo = [
-                       'version'           => '2.0',
-                       'software'          => [
+                       'version'  => '2.0',
+                       'software' => [
                                'name'    => 'friendica',
                                'version' => FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
                        ],
                        'protocols'         => ['dfrn', 'activitypub'],
                        'services'          => [],
                        'usage'             => [],
-                       'openRegistrations' => intval($config->get('config', 'register_policy')) !== Register::CLOSED,
+                       'openRegistrations' => intval($this->config->get('config', 'register_policy')) !== Register::CLOSED,
                        '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';
                }
 
-               if (empty($config->get('system', 'ostatus_disabled'))) {
+               if (empty($this->config->get('system', 'ostatus_disabled'))) {
                        $nodeinfo['protocols'][] = 'ostatus';
                }
 
@@ -72,12 +84,13 @@ class NodeInfo120 extends BaseModule
                $nodeinfo['services']['inbound'][]  = 'rss2.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['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));
        }
 }
index 3584e19d7380d8215ce454a393ea5f42aca37e6a..a354046254d5394127a411135a3d5bc1c3107de8 100644 (file)
 
 namespace Friendica\Module;
 
+use Friendica\App;
 use Friendica\BaseModule;
 use Friendica\Core\Addon;
+use Friendica\Core\Config\Capability\IManageConfigValues;
+use Friendica\Core\L10n;
 use Friendica\Core\System;
-use Friendica\DI;
 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.
@@ -33,30 +37,38 @@ use Friendica\Model\Nodeinfo;
  */
 class NodeInfo210 extends BaseModule
 {
-       protected function rawContent(array $request = [])
+       /** @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 = [])
        {
-               $config = DI::config();
+               parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
+
+               $this->config = $config;
+       }
 
+       protected function rawContent(array $request = [])
+       {
                $nodeinfo = [
-                       'version'           => '1.0',
-                       'server'          => [
-                               'baseUrl'  => DI::baseUrl()->get(),
-                               'name'     => $config->get('config', 'sitename'),
+                       'version' => '1.0',
+                       'server'  => [
+                               'baseUrl'  => $this->baseUrl->get(),
+                               'name'     => $this->config->get('config', 'sitename'),
                                'software' => 'friendica',
                                'version'  => FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
                        ],
-                       'organization'      => Nodeinfo::getOrganization($config),
+                       'organization'      => Nodeinfo::getOrganization($this->config),
                        'protocols'         => ['dfrn', 'activitypub'],
                        'services'          => [],
-                       'openRegistrations' => intval($config->get('config', 'register_policy')) !== Register::CLOSED,
+                       'openRegistrations' => intval($this->config->get('config', 'register_policy')) !== Register::CLOSED,
                        'usage'             => [],
                ];
 
-               if (!empty($config->get('system', 'diaspora_enabled'))) {
+               if (!empty($this->config->get('system', 'diaspora_enabled'))) {
                        $nodeinfo['protocols'][] = 'diaspora';
                }
 
-               if (empty($config->get('system', 'ostatus_disabled'))) {
+               if (empty($this->config->get('system', 'ostatus_disabled'))) {
                        $nodeinfo['protocols'][] = 'ostatus';
                }
 
@@ -72,7 +84,7 @@ class NodeInfo210 extends BaseModule
                $nodeinfo['services']['inbound'][]  = 'rss2.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';
                }
 
index 87fbbf07cc81e4579e0d99ea2d57f6ab0b87a5fd..4cf9f9667e1aff4dd404c9302e3f4961ef7099f3 100644 (file)
@@ -2,14 +2,14 @@
 
 namespace Friendica\Module;
 
-use Friendica\Capabilities\ICanReadAndWriteToResponds;
+use Friendica\Capabilities\ICanCreateResponses;
 use Friendica\Capabilities\IRespondToRequests;
 use Friendica\Network\HTTPException\InternalServerErrorException;
 
-class Response implements ICanReadAndWriteToResponds
+class Response implements ICanCreateResponses
 {
        /**
-        * @var string[][]
+        * @var string[]
         */
        protected $headers = [];
        /**
@@ -19,20 +19,30 @@ class Response implements ICanReadAndWriteToResponds
        /**
         * @var string
         */
-       protected $type = IRespondToRequests::TYPE_CONTENT;
+       protected $type = IRespondToRequests::TYPE_HTML;
 
        /**
         * {@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}
         */
-       public function addContent(string $content)
+       public function addContent($content): void
        {
                $this->content .= $content;
        }
@@ -48,7 +58,7 @@ class Response implements ICanReadAndWriteToResponds
        /**
         * {@inheritDoc}
         */
-       public function getContent(): string
+       public function getContent()
        {
                return $this->content;
        }
@@ -56,19 +66,31 @@ class Response implements ICanReadAndWriteToResponds
        /**
         * {@inheritDoc}
         */
-       public function setType(string $type)
+       public function setType(string $type, ?string $content_type = null): void
        {
                if (!in_array($type, IRespondToRequests::ALLOWED_TYPES)) {
                        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;
        }
 
        /**
         * {@inheritDoc}
         */
-       public function getTyp(): string
+       public function getType(): string
        {
                return $this->type;
        }
index cc1402c7a6afdf61151bc95c3972e958a16653a8..a702c17fda87233404f373a966d55c63f16570b5 100644 (file)
@@ -28,7 +28,7 @@ class ApiResponseDouble extends ApiResponse
        /**
         * The header list
         *
-        * @var string[]
+        * @var string[][]
         */
        protected static $header = [];
 
@@ -61,9 +61,22 @@ class ApiResponseDouble extends ApiResponse
                self::$header = [];
        }
 
-       protected function setHeader(string $header)
+       /**
+        * {@inheritDoc}
+        */
+       public function setHeader(?string $header = null, ?string $key = null): void
        {
-               static::$header[] = $header;
+               if (!isset($header) && !empty($key)) {
+                       unset(static::$header[$key]);
+               }
+
+               if (isset($header)) {
+                       if (empty($key)) {
+                               static::$header[] = $header;
+                       } else {
+                               static::$header[$key] = $header;
+                       }
+               }
        }
 
        protected function printOutput(string $output)
index 524c9ebd17f15fa3e911e17cac07a7af1ccacbd4..aba8c808a55b0a485353888be720ce6c0ae21a9e 100644 (file)
@@ -6,19 +6,12 @@ use Friendica\App\Arguments;
 use Friendica\App\BaseURL;
 use Friendica\Core\L10n;
 use Friendica\Factory\Api\Twitter\User;
+use Friendica\Module\Api\ApiResponse;
 use Friendica\Test\MockedTest;
-use Friendica\Test\Util\ApiResponseDouble;
 use Psr\Log\NullLogger;
 
 class ApiResponseTest extends MockedTest
 {
-       protected function tearDown(): void
-       {
-               ApiResponseDouble::reset();
-
-               parent::tearDown();
-       }
-
        public function testErrorWithJson()
        {
                $l10n = \Mockery::mock(L10n::class);
@@ -27,10 +20,10 @@ class ApiResponseTest extends MockedTest
                $baseUrl     = \Mockery::mock(BaseURL::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');
 
-               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()
@@ -41,7 +34,7 @@ class ApiResponseTest extends MockedTest
                $baseUrl     = \Mockery::mock(BaseURL::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');
 
                self::assertEquals('<?xml version="1.0"?>' . "\n" .
@@ -52,7 +45,7 @@ class ApiResponseTest extends MockedTest
                                                   '  <code>200 OK</code>' . "\n" .
                                                   '  <request/>' . "\n" .
                                                   '</status>' . "\n",
-                       ApiResponseDouble::getOutput());
+                       $response->getContent());
        }
 
        public function testErrorWithRss()
@@ -63,7 +56,7 @@ class ApiResponseTest extends MockedTest
                $baseUrl     = \Mockery::mock(BaseURL::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');
 
                self::assertEquals(
@@ -75,7 +68,7 @@ class ApiResponseTest extends MockedTest
                        '  <code>200 OK</code>' . "\n" .
                        '  <request/>' . "\n" .
                        '</status>' . "\n",
-                       ApiResponseDouble::getOutput());
+                       $response->getContent());
        }
 
        public function testErrorWithAtom()
@@ -86,7 +79,7 @@ class ApiResponseTest extends MockedTest
                $baseUrl     = \Mockery::mock(BaseURL::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');
 
                self::assertEquals(
@@ -98,7 +91,7 @@ class ApiResponseTest extends MockedTest
                        '  <code>200 OK</code>' . "\n" .
                        '  <request/>' . "\n" .
                        '</status>' . "\n",
-                       ApiResponseDouble::getOutput());
+                       $response->getContent());
        }
 
        public function testUnsupported()
@@ -112,9 +105,9 @@ class ApiResponseTest extends MockedTest
                $baseUrl     = \Mockery::mock(BaseURL::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();
 
-               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());
        }
 }
index e168c26555d774bd93bf30db75543daa056f30f9..c530ace2ee71ba69fe9803046dff2769380b3e3a 100644 (file)
@@ -25,10 +25,8 @@ use Friendica\Core\Addon;
 use Friendica\Core\Hook;
 use Friendica\Database\Database;
 use Friendica\DI;
-use Friendica\Module\Api\ApiResponse;
 use Friendica\Security\Authentication;
 use Friendica\Test\FixtureTest;
-use Friendica\Test\Util\ApiResponseDouble;
 use Friendica\Test\Util\AuthenticationDouble;
 
 abstract class ApiTest extends FixtureTest
@@ -53,20 +51,12 @@ abstract class ApiTest extends FixtureTest
                parent::setUp(); // TODO: Change the autogenerated stub
 
                $this->dice = $this->dice
-                       ->addRule(Authentication::class, ['instanceOf' => AuthenticationDouble::class, 'shared' => true])
-                       ->addRule(ApiResponse::class, ['instanceOf' => ApiResponseDouble::class, 'shared' => true]);
+                       ->addRule(Authentication::class, ['instanceOf' => AuthenticationDouble::class, 'shared' => true]);
                DI::init($this->dice);
 
                $this->installAuthTest();
        }
 
-       protected function tearDown(): void
-       {
-               ApiResponseDouble::reset();
-
-               parent::tearDown();
-       }
-
        /**
         * installs auththest.
         *
index 125e7d63d0e03700ba1c1248e0144c554296be27..b78715864ec53002492d19d4cebe621b9d0596a9 100644 (file)
@@ -23,9 +23,7 @@ namespace Friendica\Test\src\Module\Api\Friendica;
 
 use Friendica\DI;
 use Friendica\Module\Api\Friendica\Notification;
-use Friendica\Network\HTTPException\BadRequestException;
 use Friendica\Test\src\Module\Api\ApiTest;
-use Friendica\Test\Util\ApiResponseDouble;
 use Friendica\Util\DateTimeFormat;
 use Friendica\Util\Temporal;
 
@@ -67,19 +65,17 @@ class NotificationTest extends ApiTest
 </notes>
 XML;
 
-               $notification = new Notification(DI::l10n(), ['extension' => 'xml']);
-               $notification->rawContent();
+               $notification = new Notification(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), [], ['extension' => 'xml']);
+               $response = $notification->run();
 
-               self::assertXmlStringEqualsXmlString($assertXml, ApiResponseDouble::getOutput());
+               self::assertXmlStringEqualsXmlString($assertXml, $response->getContent());
        }
 
        public function testWithJsonResult()
        {
-               $notification = new Notification(DI::l10n(),['parameter' => 'json']);
-               $notification->rawContent();
+               $notification = new Notification(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), [], ['extension' => 'json']);
+               $response = $notification->run();
 
-               $result = json_encode(ApiResponseDouble::getOutput());
-
-               self::assertJson($result);
+               self::assertJson($response->getContent());
        }
 }
index 0958110115d14d2eaf72bb1d66cb77dcda049ddb..42e3f77c04ffbb837ab08bee5256b92562737a44 100644 (file)
@@ -31,7 +31,7 @@ class DeleteTest extends ApiTest
        public function testEmpty()
        {
                $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()
@@ -42,7 +42,7 @@ class DeleteTest extends ApiTest
        public function testWrong()
        {
                $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()
index aabd7e581c95b9336ad24e572c3402ac092d3386..118257c55bb6b3b55f7c95722a2a32fe54a6c9e2 100644 (file)
@@ -31,13 +31,14 @@ class DeleteTest extends ApiTest
        public function testEmpty()
        {
                $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()
        {
                $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()
index 51414302fa52e3f38b4faf0d0956a489f1d6acde..464845745fa9e4cd62775fbc34a09121987f9d51 100644 (file)
@@ -31,19 +31,19 @@ class UpdateTest extends ApiTest
        public function testEmpty()
        {
                $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()
        {
                $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()
        {
                $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()
index 448f6ce1453c91bf5ba77d0d2ab3b413a0e80ab3..88bce964cadf0638aae1d9769d03053ddb493da3 100644 (file)
@@ -5,17 +5,14 @@ namespace Friendica\Test\src\Module\Api\GnuSocial\GnuSocial;
 use Friendica\DI;
 use Friendica\Module\Api\GNUSocial\GNUSocial\Version;
 use Friendica\Test\src\Module\Api\ApiTest;
-use Friendica\Test\Util\ApiResponseDouble;
 
 class VersionTest extends ApiTest
 {
        public function test()
        {
-               $version = new Version(DI::l10n(), ['extension' => 'json']);
-               $version->rawContent();
+               $version = new Version(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), [], ['extension' => 'json']);
+               $response = $version->run();
 
-               $result = json_decode(ApiResponseDouble::getOutput());
-
-               self::assertEquals('0.9.7', $result);
+               self::assertEquals('"0.9.7"', $response->getContent());
        }
 }
index 40d8e9750e1e79eea305ccd267d879aacb3edba4..82ceefec9bc03d53fe9f02baf67782c050c8aab4 100644 (file)
@@ -5,23 +5,22 @@ namespace Friendica\Test\src\Module\Api\GnuSocial\Help;
 use Friendica\DI;
 use Friendica\Module\Api\GNUSocial\Help\Test;
 use Friendica\Test\src\Module\Api\ApiTest;
-use Friendica\Test\Util\ApiResponseDouble;
 
 class TestTest extends ApiTest
 {
        public function testJson()
        {
-               $test = new Test(DI::l10n(), ['extension' => 'json']);
-               $test->rawContent();
+               $test = new Test(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), [], ['extension' => 'json']);
+               $response = $test->run();
 
-               self::assertEquals('"ok"', ApiResponseDouble::getOutput());
+               self::assertEquals('"ok"', $response->getContent());
        }
 
        public function testXml()
        {
-               $test = new Test(DI::l10n(), ['extension' => 'xml']);
-               $test->rawContent();
+               $test = new Test(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), [], ['extension' => 'xml']);
+               $response = $test->run();
 
-               self::assertxml(ApiResponseDouble::getOutput(), 'ok');
+               self::assertxml($response->getContent(), 'ok');
        }
 }
index 93d76933ba6c40ee0c8cfbc00ae06b76c5d882c8..66821cea1656985a11d550524c41f21304df7c1c 100644 (file)
@@ -5,16 +5,15 @@ namespace Friendica\Test\src\Module\Api\Twitter\Account;
 use Friendica\DI;
 use Friendica\Module\Api\Twitter\Account\RateLimitStatus;
 use Friendica\Test\src\Module\Api\ApiTest;
-use Friendica\Test\Util\ApiResponseDouble;
 
 class RateLimitStatusTest extends ApiTest
 {
        public function testWithJson()
        {
-               $rateLimitStatus = new RateLimitStatus(DI::l10n(), ['extension' => 'json']);
-               $rateLimitStatus->rawContent();
+               $rateLimitStatus = new RateLimitStatus(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), [], ['extension' => 'json']);
+               $response = $rateLimitStatus->run();
 
-               $result = json_decode(ApiResponseDouble::getOutput());
+               $result = json_decode($response->getContent());
 
                self::assertEquals(150, $result->remaining_hits);
                self::assertEquals(150, $result->hourly_limit);
@@ -23,9 +22,9 @@ class RateLimitStatusTest extends ApiTest
 
        public function testWithXml()
        {
-               $rateLimitStatus = new RateLimitStatus(DI::l10n(),['extension' => 'xml']);
-               $rateLimitStatus->rawContent();
+               $rateLimitStatus = new RateLimitStatus(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), [], ['extension' => 'xml']);
+               $response = $rateLimitStatus->run();
 
-               self::assertXml(ApiResponseDouble::getOutput(), 'hash');
+               self::assertXml($response->getContent(), 'hash');
        }
 }
index 8e066d4bad93ed70cf826b20646936da38d29f18..497a06310665a66c72e8b661ed4c05128e58e2c1 100644 (file)
@@ -5,16 +5,15 @@ namespace Friendica\Test\src\Module\Api\Twitter;
 use Friendica\DI;
 use Friendica\Module\Api\Twitter\SavedSearches;
 use Friendica\Test\src\Module\Api\ApiTest;
-use Friendica\Test\Util\ApiResponseDouble;
 
 class SavedSearchesTest extends ApiTest
 {
        public function test()
        {
-               $savedSearch = new SavedSearches(DI::l10n(), ['extension' => 'json']);
-               $savedSearch->rawContent();
+               $savedSearch = new SavedSearches(DI::app(), DI::l10n(), DI::baseUrl(), DI::args(), DI::logger(), DI::profiler(), DI::apiResponse(), [], ['extension' => 'json']);
+               $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_str);