Replaced all FQ global function and constants by explicit imports

This commit is contained in:
Alejandro Celaya
2018-10-28 08:24:06 +01:00
parent e1222de05b
commit 77d810b735
70 changed files with 235 additions and 123 deletions

View File

@@ -8,6 +8,7 @@ use Fig\Http\Message\StatusCodeInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use function array_merge;
abstract class AbstractRestAction implements RequestHandlerInterface, RequestMethodInterface, StatusCodeInterface
{
@@ -28,7 +29,7 @@ abstract class AbstractRestAction implements RequestHandlerInterface, RequestMet
{
return [
'name' => static::class,
'middleware' => \array_merge($prevMiddleware, [static::class], $postMiddleware),
'middleware' => array_merge($prevMiddleware, [static::class], $postMiddleware),
'path' => static::ROUTE_PATH,
'allowed_methods' => static::ROUTE_ALLOWED_METHODS,
];

View File

@@ -14,8 +14,10 @@ use Shlinkio\Shlink\Core\Service\UrlShortenerInterface;
use Shlinkio\Shlink\Core\Transformer\ShortUrlDataTransformer;
use Shlinkio\Shlink\Rest\Action\AbstractRestAction;
use Shlinkio\Shlink\Rest\Util\RestUtils;
use Throwable;
use Zend\Diactoros\Response\JsonResponse;
use Zend\I18n\Translator\TranslatorInterface;
use function sprintf;
abstract class AbstractCreateShortUrlAction extends AbstractRestAction
{
@@ -80,7 +82,7 @@ abstract class AbstractCreateShortUrlAction extends AbstractRestAction
$this->logger->warning('Provided Invalid URL. {e}', ['e' => $e]);
return new JsonResponse([
'error' => RestUtils::getRestErrorCodeFromException($e),
'message' => \sprintf(
'message' => sprintf(
$this->translator->translate('Provided URL %s is invalid. Try with a different one.'),
$longUrl
),
@@ -89,12 +91,12 @@ abstract class AbstractCreateShortUrlAction extends AbstractRestAction
$this->logger->warning('Provided non-unique slug. {e}', ['e' => $e]);
return new JsonResponse([
'error' => RestUtils::getRestErrorCodeFromException($e),
'message' => \sprintf(
'message' => sprintf(
$this->translator->translate('Provided slug %s is already in use. Try with a different one.'),
$customSlug
),
], self::STATUS_BAD_REQUEST);
} catch (\Throwable $e) {
} catch (Throwable $e) {
$this->logger->error('Unexpected error creating short url. {e}', ['e' => $e]);
return new JsonResponse([
'error' => RestUtils::UNKNOWN_ERROR,

View File

@@ -13,6 +13,7 @@ use Shlinkio\Shlink\Rest\Util\RestUtils;
use Zend\Diactoros\Response\EmptyResponse;
use Zend\Diactoros\Response\JsonResponse;
use Zend\I18n\Translator\TranslatorInterface;
use function sprintf;
class DeleteShortUrlAction extends AbstractRestAction
{
@@ -55,7 +56,7 @@ class DeleteShortUrlAction extends AbstractRestAction
);
return new JsonResponse([
'error' => RestUtils::getRestErrorCodeFromException($e),
'message' => \sprintf($this->translator->translate('No URL found for short code "%s"'), $shortCode),
'message' => sprintf($this->translator->translate('No URL found for short code "%s"'), $shortCode),
], self::STATUS_NOT_FOUND);
} catch (Exception\DeleteShortUrlException $e) {
$this->logger->warning('Provided data is invalid. {e}', ['e' => $e]);
@@ -65,7 +66,7 @@ class DeleteShortUrlAction extends AbstractRestAction
return new JsonResponse([
'error' => RestUtils::getRestErrorCodeFromException($e),
'message' => \sprintf($messagePlaceholder, $shortCode, $e->getVisitsThreshold()),
'message' => sprintf($messagePlaceholder, $shortCode, $e->getVisitsThreshold()),
], self::STATUS_BAD_REQUEST);
}
}

View File

@@ -14,6 +14,7 @@ use Shlinkio\Shlink\Rest\Util\RestUtils;
use Zend\Diactoros\Response\EmptyResponse;
use Zend\Diactoros\Response\JsonResponse;
use Zend\I18n\Translator\TranslatorInterface;
use function sprintf;
class EditShortUrlAction extends AbstractRestAction
{
@@ -63,7 +64,7 @@ class EditShortUrlAction extends AbstractRestAction
$this->logger->warning('Provided data is invalid. {e}', ['e' => $e]);
return new JsonResponse([
'error' => RestUtils::getRestErrorCodeFromException($e),
'message' => \sprintf($this->translator->translate('No URL found for short code "%s"'), $shortCode),
'message' => sprintf($this->translator->translate('No URL found for short code "%s"'), $shortCode),
], self::STATUS_NOT_FOUND);
} catch (Exception\ValidationException $e) {
$this->logger->warning('Provided data is invalid. {e}', ['e' => $e]);

View File

@@ -3,6 +3,7 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Rest\Action\ShortUrl;
use Exception;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Log\LoggerInterface;
@@ -59,7 +60,7 @@ class ListShortUrlsAction extends AbstractRestAction
return new JsonResponse(['shortUrls' => $this->serializePaginator($shortUrls, new ShortUrlDataTransformer(
$this->domainConfig
))]);
} catch (\Exception $e) {
} catch (Exception $e) {
$this->logger->error('Unexpected error while listing short URLs. {e}', ['e' => $e]);
return new JsonResponse([
'error' => RestUtils::UNKNOWN_ERROR,

View File

@@ -3,6 +3,7 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Rest\Action\ShortUrl;
use Exception;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Log\LoggerInterface;
@@ -14,6 +15,7 @@ use Shlinkio\Shlink\Rest\Action\AbstractRestAction;
use Shlinkio\Shlink\Rest\Util\RestUtils;
use Zend\Diactoros\Response\JsonResponse;
use Zend\I18n\Translator\TranslatorInterface;
use function sprintf;
class ResolveShortUrlAction extends AbstractRestAction
{
@@ -62,7 +64,7 @@ class ResolveShortUrlAction extends AbstractRestAction
$this->logger->warning('Provided short code with invalid format. {e}', ['e' => $e]);
return new JsonResponse([
'error' => RestUtils::getRestErrorCodeFromException($e),
'message' => \sprintf(
'message' => sprintf(
$this->translator->translate('Provided short code "%s" has an invalid format'),
$shortCode
),
@@ -71,9 +73,9 @@ class ResolveShortUrlAction extends AbstractRestAction
$this->logger->warning('Provided short code couldn\'t be found. {e}', ['e' => $e]);
return new JsonResponse([
'error' => RestUtils::INVALID_ARGUMENT_ERROR,
'message' => \sprintf($this->translator->translate('No URL found for short code "%s"'), $shortCode),
'message' => sprintf($this->translator->translate('No URL found for short code "%s"'), $shortCode),
], self::STATUS_NOT_FOUND);
} catch (\Exception $e) {
} catch (Exception $e) {
$this->logger->error('Unexpected error while resolving the URL behind a short code. {e}', ['e' => $e]);
return new JsonResponse([
'error' => RestUtils::UNKNOWN_ERROR,

View File

@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Rest\Action\Visit;
use Cake\Chronos\Chronos;
use Exception;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Log\LoggerInterface;
@@ -67,7 +68,7 @@ class GetVisitsAction extends AbstractRestAction
$shortCode
),
], self::STATUS_NOT_FOUND);
} catch (\Exception $e) {
} catch (Exception $e) {
$this->logger->error('Unexpected error while parsing short code {e}', ['e' => $e]);
return new JsonResponse([
'error' => RestUtils::UNKNOWN_ERROR,

View File

@@ -7,6 +7,7 @@ use Firebase\JWT\JWT;
use Shlinkio\Shlink\Core\Options\AppOptions;
use Shlinkio\Shlink\Rest\Entity\ApiKey;
use Shlinkio\Shlink\Rest\Exception\AuthenticationException;
use UnexpectedValueException;
use function time;
class JWTService implements JWTServiceInterface
@@ -68,7 +69,7 @@ class JWTService implements JWTServiceInterface
// If no exception is thrown while decoding the token, it is considered valid
$this->decode($jwt);
return true;
} catch (\UnexpectedValueException $e) {
} catch (UnexpectedValueException $e) {
return false;
}
}
@@ -84,7 +85,7 @@ class JWTService implements JWTServiceInterface
{
try {
return $this->decode($jwt);
} catch (\UnexpectedValueException $e) {
} catch (UnexpectedValueException $e) {
throw AuthenticationException::expiredJWT($e);
}
}

View File

@@ -7,7 +7,10 @@ use Acelaya\ExpressiveErrorHandler\ErrorHandler\ErrorResponseGeneratorInterface;
use Fig\Http\Message\StatusCodeInterface;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Throwable;
use Zend\Diactoros\Response\JsonResponse;
use function str_replace;
use function strtoupper;
class JsonErrorResponseGenerator implements ErrorResponseGeneratorInterface, StatusCodeInterface
{
@@ -20,7 +23,7 @@ class JsonErrorResponseGenerator implements ErrorResponseGeneratorInterface, Sta
* @return Response
* @throws \InvalidArgumentException
*/
public function __invoke(?\Throwable $e, Request $request, Response $response)
public function __invoke(?Throwable $e, Request $request, Response $response)
{
$status = $response->getStatusCode();
$responsePhrase = $status < 400 ? 'Internal Server Error' : $response->getReasonPhrase();
@@ -34,6 +37,6 @@ class JsonErrorResponseGenerator implements ErrorResponseGeneratorInterface, Sta
private function responsePhraseToCode(string $responsePhrase): string
{
return \strtoupper(\str_replace(' ', '_', $responsePhrase));
return strtoupper(str_replace(' ', '_', $responsePhrase));
}
}

View File

@@ -3,9 +3,11 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Rest\Exception;
use Exception;
class AuthenticationException extends RuntimeException
{
public static function expiredJWT(\Exception $prev = null): self
public static function expiredJWT(Exception $prev = null): self
{
return new self('The token has expired.', -1, $prev);
}

View File

@@ -3,6 +3,8 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Rest\Exception;
interface ExceptionInterface extends \Throwable
use Throwable;
interface ExceptionInterface extends Throwable
{
}

View File

@@ -3,6 +3,8 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Rest\Exception;
class RuntimeException extends \RuntimeException implements ExceptionInterface
use RuntimeException as SplRuntimeException;
class RuntimeException extends SplRuntimeException implements ExceptionInterface
{
}

View File

@@ -7,6 +7,7 @@ use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use function strpos;
class PathVersionMiddleware implements MiddlewareInterface
{
@@ -26,7 +27,7 @@ class PathVersionMiddleware implements MiddlewareInterface
$path = $uri->getPath();
// If the path does not begin with the version number, prepend v1 by default for BC compatibility purposes
if (\strpos($path, '/v') !== 0) {
if (strpos($path, '/v') !== 0) {
$request = $request->withUri($uri->withPath('/v1' . $uri->getPath()));
}

View File

@@ -9,6 +9,10 @@ use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Zend\Diactoros\Response;
use Zend\Diactoros\Response\JsonResponse;
use function array_shift;
use function explode;
use function strpos;
use function strtolower;
class CreateShortUrlContentNegotiationMiddleware implements MiddlewareInterface
{
@@ -54,15 +58,15 @@ class CreateShortUrlContentNegotiationMiddleware implements MiddlewareInterface
return self::JSON;
}
$format = \strtolower((string) $query['format']);
$format = strtolower((string) $query['format']);
return $format === 'txt' ? self::PLAIN_TEXT : self::JSON;
}
private function determineAcceptTypeFromHeader(string $acceptValue): string
{
$accepts = \explode(',', $acceptValue);
$accept = \strtolower(\array_shift($accepts));
return \strpos($accept, 'text/plain') !== false ? self::PLAIN_TEXT : self::JSON;
$accepts = explode(',', $acceptValue);
$accept = strtolower(array_shift($accepts));
return strpos($accept, 'text/plain') !== false ? self::PLAIN_TEXT : self::JSON;
}
private function determineBody(JsonResponse $resp): string

View File

@@ -7,6 +7,7 @@ use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use function str_replace;
class ShortCodePathMiddleware implements MiddlewareInterface
{
@@ -24,7 +25,7 @@ class ShortCodePathMiddleware implements MiddlewareInterface
// If the path starts with the old prefix, replace it by the new one
return $handler->handle(
$request->withUri($uri->withPath(\str_replace(self::OLD_PATH_PREFIX, self::NEW_PATH_PREFIX, $path)))
$request->withUri($uri->withPath(str_replace(self::OLD_PATH_PREFIX, self::NEW_PATH_PREFIX, $path)))
);
}
}

View File

@@ -6,6 +6,7 @@ namespace Shlinkio\Shlink\Rest\Util;
use Shlinkio\Shlink\Common\Exception as Common;
use Shlinkio\Shlink\Core\Exception as Core;
use Shlinkio\Shlink\Rest\Exception as Rest;
use Throwable;
class RestUtils
{
@@ -22,7 +23,7 @@ class RestUtils
public const NOT_FOUND_ERROR = 'NOT_FOUND';
public const UNKNOWN_ERROR = 'UNKNOWN_ERROR';
public static function getRestErrorCodeFromException(\Throwable $e)
public static function getRestErrorCodeFromException(Throwable $e)
{
switch (true) {
case $e instanceof Core\InvalidShortCodeException:

View File

@@ -3,6 +3,7 @@ declare(strict_types=1);
namespace ShlinkioTest\Shlink\Rest\Action\ShortUrl;
use Exception;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Prophecy\Prophecy\ObjectProphecy;
@@ -111,7 +112,7 @@ class CreateShortUrlActionTest extends TestCase
public function aGenericExceptionWillReturnError()
{
$this->urlShortener->urlToShortCode(Argument::type(Uri::class), Argument::type('array'), Argument::cetera())
->willThrow(\Exception::class)
->willThrow(Exception::class)
->shouldBeCalledTimes(1);
$request = ServerRequestFactory::fromGlobals()->withParsedBody([

View File

@@ -10,6 +10,7 @@ use Shlinkio\Shlink\Core\Exception;
use Shlinkio\Shlink\Core\Service\ShortUrl\DeleteShortUrlServiceInterface;
use Shlinkio\Shlink\Rest\Action\ShortUrl\DeleteShortUrlAction;
use Shlinkio\Shlink\Rest\Util\RestUtils;
use Throwable;
use Zend\Diactoros\Response\JsonResponse;
use Zend\Diactoros\ServerRequestFactory;
use Zend\I18n\Translator\Translator;
@@ -49,7 +50,7 @@ class DeleteShortUrlActionTest extends TestCase
* @test
* @dataProvider provideExceptions
*/
public function returnsErrorResponseInCaseOfException(\Throwable $e, string $error, int $statusCode)
public function returnsErrorResponseInCaseOfException(Throwable $e, string $error, int $statusCode)
{
$deleteByShortCode = $this->service->deleteByShortCode(Argument::any())->willThrow($e);

View File

@@ -3,6 +3,7 @@ declare(strict_types=1);
namespace ShlinkioTest\Shlink\Rest\Action\ShortUrl;
use Exception;
use PHPUnit\Framework\TestCase;
use Prophecy\Prophecy\ObjectProphecy;
use Shlinkio\Shlink\Core\Service\ShortUrlService;
@@ -53,7 +54,7 @@ class ListShortUrlsActionTest extends TestCase
public function anExceptionsReturnsErrorResponse()
{
$page = 3;
$this->service->listShortUrls($page, null, [], null)->willThrow(\Exception::class)
$this->service->listShortUrls($page, null, [], null)->willThrow(Exception::class)
->shouldBeCalledTimes(1);
$response = $this->action->handle(ServerRequestFactory::fromGlobals()->withQueryParams([

View File

@@ -3,6 +3,7 @@ declare(strict_types=1);
namespace ShlinkioTest\Shlink\Rest\Action\ShortUrl;
use Exception;
use PHPUnit\Framework\TestCase;
use Prophecy\Prophecy\ObjectProphecy;
use Shlinkio\Shlink\Core\Entity\ShortUrl;
@@ -83,7 +84,7 @@ class ResolveShortUrlActionTest extends TestCase
public function unexpectedExceptionWillReturnError()
{
$shortCode = 'abc123';
$this->urlShortener->shortCodeToUrl($shortCode)->willThrow(\Exception::class)
$this->urlShortener->shortCodeToUrl($shortCode)->willThrow(Exception::class)
->shouldBeCalledTimes(1);
$request = ServerRequestFactory::fromGlobals()->withAttribute('shortCode', $shortCode);

View File

@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace ShlinkioTest\Shlink\Rest\Action\Visit;
use Cake\Chronos\Chronos;
use Exception;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Prophecy\Prophecy\ObjectProphecy;
@@ -65,7 +66,7 @@ class GetVisitsActionTest extends TestCase
{
$shortCode = 'abc123';
$this->visitsTracker->info($shortCode, Argument::type(DateRange::class))->willThrow(
\Exception::class
Exception::class
)->shouldBeCalledTimes(1);
$response = $this->action->handle(ServerRequestFactory::fromGlobals()->withAttribute('shortCode', $shortCode));

View File

@@ -12,6 +12,7 @@ use Shlinkio\Shlink\Rest\Middleware\PathVersionMiddleware;
use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequestFactory;
use Zend\Diactoros\Uri;
use function array_shift;
class PathVersionMiddlewareTest extends TestCase
{
@@ -49,7 +50,7 @@ class PathVersionMiddlewareTest extends TestCase
$delegate = $this->prophesize(RequestHandlerInterface::class);
$delegate->handle(Argument::type(Request::class))->will(function (array $args) use ($request) {
$req = \array_shift($args);
$req = array_shift($args);
Assert::assertNotSame($request, $req);
Assert::assertEquals('/v1/bar/baz', $req->getUri()->getPath());