Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Slim4 #1972

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
15 changes: 9 additions & 6 deletions application/Languages.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,17 +96,19 @@ protected function initGettextTranslator()
{
$this->translator = new GettextTranslator();
$this->translator->setLanguage($this->language);
$this->translator->loadDomain(self::DEFAULT_DOMAIN, 'inc/languages');
$this->translator->loadDomain(self::DEFAULT_DOMAIN, __DIR__ . '/../inc/languages');

// Default extension translation from the current theme
$themeTransFolder = rtrim($this->conf->get('raintpl_tpl'), '/') . '/' . $this->conf->get('theme') . '/language';
$themeTransFolder = __DIR__ . '/../' . rtrim($this->conf->get('raintpl_tpl'), '/') . '/'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not convinced that we have to change how we are handling paths for the translator. Not that it's shouldn't be done if there are pros of doing so, but it could introduce bugs and I don't think it affects Slim.

. $this->conf->get('theme') . '/language';
if (is_dir($themeTransFolder)) {
$this->translator->loadDomain($this->conf->get('theme'), $themeTransFolder, false);
}

foreach ($this->conf->get('translation.extensions', []) as $domain => $translationPath) {
$path = __DIR__ . '/../' . $translationPath;
if ($domain !== self::DEFAULT_DOMAIN) {
$this->translator->loadDomain($domain, $translationPath, false);
$this->translator->loadDomain($domain, $path, false);
}
}
}
Expand All @@ -123,7 +125,7 @@ protected function initPhpTranslator()
// Core translations
try {
$translations = $translations->addFromPoFile(
'inc/languages/' . $this->language . '/LC_MESSAGES/shaarli.po'
__DIR__ . '/../inc/languages/' . $this->language . '/LC_MESSAGES/shaarli.po'
);
$translations->setDomain('shaarli');
$this->translator->loadTranslations($translations);
Expand All @@ -132,7 +134,8 @@ protected function initPhpTranslator()

// Default extension translation from the current theme
$theme = $this->conf->get('theme');
$themeTransFolder = rtrim($this->conf->get('raintpl_tpl'), '/') . '/' . $theme . '/language';
$themeTransFolder = __DIR__ . '/../' . rtrim($this->conf->get('raintpl_tpl'), '/') . '/'
. $theme . '/language';
if (is_dir($themeTransFolder)) {
try {
$translations = Translations::fromPoFile(
Expand All @@ -152,7 +155,7 @@ protected function initPhpTranslator()

try {
$extension = Translations::fromPoFile(
$translationPath . $this->language . '/LC_MESSAGES/' . $domain . '.po'
__DIR__ . '/../' . $translationPath . $this->language . '/LC_MESSAGES/' . $domain . '.po'
);
$extension->setDomain($domain);
$this->translator->loadTranslations($extension);
Expand Down
22 changes: 11 additions & 11 deletions application/api/ApiMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
namespace Shaarli\Api;

use malkusch\lock\mutex\FlockMutex;
use Psr\Container\ContainerInterface as Container;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Shaarli\Api\Exceptions\ApiAuthorizationException;
use Shaarli\Api\Exceptions\ApiException;
use Shaarli\Bookmark\BookmarkFileService;
use Shaarli\Config\ConfigManager;
use Slim\Container;
use Slim\Http\Request;
use Slim\Http\Response;

/**
* Class ApiMiddleware
Expand Down Expand Up @@ -43,7 +44,7 @@ class ApiMiddleware
*
* @param Container $container instance.
*/
public function __construct($container)
public function __construct(Container $container)
{
$this->container = $container;
$this->conf = $this->container->get('conf');
Expand All @@ -62,13 +63,12 @@ public function __construct($container)
*
* @return Response response.
*/
public function __invoke($request, $response, $next)
public function __invoke(Request $request, RequestHandler $handler): Response
{
try {
$this->checkRequest($request);
$response = $next($request, $response);
$response = $handler->handle($request);
} catch (ApiException $e) {
$e->setResponse($response);
$e->setDebug($this->conf->get('dev.debug', false));
$response = $e->getApiResponse();
}
Expand Down Expand Up @@ -111,7 +111,7 @@ protected function checkToken($request)
{
if (
!$request->hasHeader('Authorization')
&& !isset($this->container->environment['REDIRECT_HTTP_AUTHORIZATION'])
&& !isset($request->getServerParams()['REDIRECT_HTTP_AUTHORIZATION'])
) {
throw new ApiAuthorizationException('JWT token not provided');
}
Expand All @@ -120,8 +120,8 @@ protected function checkToken($request)
throw new ApiAuthorizationException('Token secret must be set in Shaarli\'s administration');
}

if (isset($this->container->environment['REDIRECT_HTTP_AUTHORIZATION'])) {
$authorization = $this->container->environment['REDIRECT_HTTP_AUTHORIZATION'];
if (isset($request->getServerParams()['REDIRECT_HTTP_AUTHORIZATION'])) {
$authorization = $request->getServerParams()['REDIRECT_HTTP_AUTHORIZATION'];
} else {
$authorization = $request->getHeaderLine('Authorization');
}
Expand Down Expand Up @@ -150,6 +150,6 @@ protected function setLinkDb($conf)
new FlockMutex(fopen(SHAARLI_MUTEX_FILE, 'r'), 2),
true
);
$this->container['db'] = $linkDb;
$this->container->set('db', $linkDb);
}
}
18 changes: 17 additions & 1 deletion application/api/controllers/ApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@

namespace Shaarli\Api\Controllers;

use DI\Container;
use Psr\Http\Message\ResponseInterface as Response;
use Shaarli\Bookmark\BookmarkServiceInterface;
use Shaarli\Config\ConfigManager;
use Shaarli\History;
use Slim\Container;

/**
* Abstract Class ApiController
Expand Down Expand Up @@ -70,4 +71,19 @@ public function getCi()
{
return $this->ci;
}

/**
* Simple helper, which writes data as JSON to the body
*
* @param Response $response
* @param array $data
* @param ?int $jsonStyle
* @return Response
*/
protected function respondWithJson(Response $response, array $data, ?int $jsonStyle): Response
{
$jsonStyle = $jsonStyle ?? 0;
$response->getBody()->write(json_encode($data, $jsonStyle));
return $response->withHeader('Content-Type', 'application/json');
}
}
13 changes: 7 additions & 6 deletions application/api/controllers/HistoryController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

namespace Shaarli\Api\Controllers;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Shaarli\Api\Exceptions\ApiBadParametersException;
use Slim\Http\Request;
use Slim\Http\Response;
use Shaarli\ResponseUtils;

/**
* Class History
Expand All @@ -30,8 +31,8 @@ public function getHistory($request, $response)
$history = $this->history->getHistory();

// Return history operations from the {offset}th, starting from {since}.
$since = \DateTime::createFromFormat(\DateTime::ATOM, $request->getParam('since', ''));
$offset = $request->getParam('offset');
$since = \DateTime::createFromFormat(\DateTime::ATOM, $request->getQueryParams()['since'] ?? '');
$offset = $request->getQueryParams()['offset'] ?? null;
if (empty($offset)) {
$offset = 0;
} elseif (ctype_digit($offset)) {
Expand All @@ -41,7 +42,7 @@ public function getHistory($request, $response)
}

// limit parameter is either a number of bookmarks or 'all' for everything.
$limit = $request->getParam('limit');
$limit = $request->getQueryParams()['limit'] ?? null;
if (empty($limit)) {
$limit = count($history);
} elseif (ctype_digit($limit)) {
Expand All @@ -63,6 +64,6 @@ public function getHistory($request, $response)
}
$out = array_values($out);

return $response->withJson($out, 200, $this->jsonStyle);
return $this->respondWithJson($response, $out, $this->jsonStyle)->withStatus(200);
}
}
7 changes: 4 additions & 3 deletions application/api/controllers/Info.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

namespace Shaarli\Api\Controllers;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Shaarli\Bookmark\BookmarkFilter;
use Slim\Http\Request;
use Slim\Http\Response;
use Shaarli\ResponseUtils;

/**
* Class Info
Expand Down Expand Up @@ -38,6 +39,6 @@ public function getInfo($request, $response)
],
];

return $response->withJson($info, 200, $this->jsonStyle);
return $this->respondWithJson($response, $info, $this->jsonStyle)->withStatus(200);
}
}
52 changes: 28 additions & 24 deletions application/api/controllers/Links.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@

namespace Shaarli\Api\Controllers;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Shaarli\Api\ApiUtils;
use Shaarli\Api\Exceptions\ApiBadParametersException;
use Shaarli\Api\Exceptions\ApiLinkNotFoundException;
use Slim\Http\Request;
use Slim\Http\Response;
use Slim\Routing\RouteContext;

/**
* Class Links
Expand Down Expand Up @@ -35,17 +36,17 @@ class Links extends ApiController
*/
public function getLinks($request, $response)
{
$private = $request->getParam('visibility');
$private = $request->getQueryParams()['visibility'] ?? null;

// Return bookmarks from the {offset}th link, starting from 0.
$offset = $request->getParam('offset');
$offset = $request->getQueryParams()['offset'] ?? null;
if (! empty($offset) && ! ctype_digit($offset)) {
throw new ApiBadParametersException('Invalid offset');
}
$offset = ! empty($offset) ? intval($offset) : 0;

// limit parameter is either a number of bookmarks or 'all' for everything.
$limit = $request->getParam('limit');
$limit = $request->getQueryParams()['limit'] ?? null;
if (empty($limit)) {
$limit = self::$DEFAULT_LIMIT;
} elseif (ctype_digit($limit)) {
Expand All @@ -58,8 +59,8 @@ public function getLinks($request, $response)

$searchResult = $this->bookmarkService->search(
[
'searchtags' => $request->getParam('searchtags', ''),
'searchterm' => $request->getParam('searchterm', ''),
'searchtags' => $request->getQueryParams()['searchtags'] ?? '',
'searchterm' => $request->getQueryParams()['searchterm'] ?? '',
],
$private,
false,
Expand All @@ -73,14 +74,14 @@ public function getLinks($request, $response)
);

// 'environment' is set by Slim and encapsulate $_SERVER.
$indexUrl = index_url($this->ci['environment']);
$indexUrl = index_url($request->getServerParams());

$out = [];
foreach ($searchResult->getBookmarks() as $bookmark) {
$out[] = ApiUtils::formatLink($bookmark, $indexUrl);
}

return $response->withJson($out, 200, $this->jsonStyle);
return $this->respondWithJson($response, $out, $this->jsonStyle)->withStatus(200);
}

/**
Expand All @@ -100,10 +101,10 @@ public function getLink($request, $response, $args)
if ($id === null || ! $this->bookmarkService->exists($id)) {
throw new ApiLinkNotFoundException();
}
$index = index_url($this->ci['environment']);
$index = index_url($request->getServerParams());
$out = ApiUtils::formatLink($this->bookmarkService->get($id), $index);

return $response->withJson($out, 200, $this->jsonStyle);
return $this->respondWithJson($response, $out, $this->jsonStyle)->withStatus(200);
}

/**
Expand All @@ -127,18 +128,20 @@ public function postLink($request, $response)
! empty($bookmark->getUrl())
&& ! empty($dup = $this->bookmarkService->findByUrl($bookmark->getUrl()))
) {
return $response->withJson(
ApiUtils::formatLink($dup, index_url($this->ci['environment'])),
409,
return $this->respondWithJson(
$response,
ApiUtils::formatLink($dup, index_url($request->getServerParams())),
$this->jsonStyle
);
)->withStatus(409);
}

$this->bookmarkService->add($bookmark);
$out = ApiUtils::formatLink($bookmark, index_url($this->ci['environment']));
$redirect = $this->ci->router->pathFor('getLink', ['id' => $bookmark->getId()]);
return $response->withAddedHeader('Location', $redirect)
->withJson($out, 201, $this->jsonStyle);
$out = ApiUtils::formatLink($bookmark, index_url($request->getServerParams()));
$routeParser = $request->getAttribute(RouteContext::ROUTE_PARSER);
$redirect = $routeParser->relativeUrlFor('getLink', ['id' => $bookmark->getId()]);

return $this->respondWithJson($response, $out, $this->jsonStyle)
->withAddedHeader('Location', $redirect)->withStatus(201);
}

/**
Expand All @@ -159,7 +162,7 @@ public function putLink($request, $response, $args)
throw new ApiLinkNotFoundException();
}

$index = index_url($this->ci['environment']);
$index = index_url($request->getServerParams());
$data = $request->getParsedBody();

$requestBookmark = ApiUtils::buildBookmarkFromRequest(
Expand All @@ -173,19 +176,20 @@ public function putLink($request, $response, $args)
&& ! empty($dup = $this->bookmarkService->findByUrl($requestBookmark->getUrl()))
&& $dup->getId() != $id
) {
return $response->withJson(
return $this->respondWithJson(
$response,
ApiUtils::formatLink($dup, $index),
409,
$this->jsonStyle
);
)->withStatus(409);
}

$responseBookmark = $this->bookmarkService->get($id);
$responseBookmark = ApiUtils::updateLink($responseBookmark, $requestBookmark);
$this->bookmarkService->set($responseBookmark);

$out = ApiUtils::formatLink($responseBookmark, $index);
return $response->withJson($out, 200, $this->jsonStyle);
return $this->respondWithJson($response, $out, $this->jsonStyle)
->withStatus(200);
}

/**
Expand Down
Loading