Merge pull request #278 from acelaya/feature/del-translations

Feature/del translations
This commit is contained in:
Alejandro Celaya 2018-11-18 20:30:53 +01:00 committed by GitHub
commit 15a70d0157
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
91 changed files with 393 additions and 1330 deletions

View file

@ -4,6 +4,29 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org).
## [Unreleased]
#### Added
* *Nothing*
#### Changed
* [#267](https://github.com/shlinkio/shlink/issues/267) API responses and the CLI interface is no longer translated and uses english always. Only not found error templates are still translated.
#### Deprecated
* *Nothing*
#### Removed
* *Nothing*
#### Fixed
* [#278](https://github.com/shlinkio/shlink/pull/278) Added missing `X-Api-Key` header to the list of valid cross domain headers.
## 1.14.1 - 2018-11-17
#### Added

View file

@ -1,8 +1,11 @@
<?php
declare(strict_types=1);
use Zend\ConfigAggregator\ConfigAggregator;
return [
'debug' => true,
'config_cache_enabled' => false,
ConfigAggregator::ENABLE_CACHE => false,
];

View file

@ -13,7 +13,6 @@ return [
'middleware' => [
ErrorHandler::class,
Expressive\Helper\ContentLengthMiddleware::class,
Common\Middleware\LocaleMiddleware::class,
],
'priority' => 12,
],
@ -47,6 +46,9 @@ return [
'post-routing' => [
'middleware' => [
Expressive\Router\Middleware\DispatchMiddleware::class,
// Only if a not found error is triggered, set-up the locale to be used
Common\Middleware\LocaleMiddleware::class,
Core\Response\NotFoundHandler::class,
],
'priority' => 1,

View file

@ -1,9 +1,11 @@
<?php
declare(strict_types=1);
use Zend\ConfigAggregator\ConfigAggregator;
return [
'debug' => false,
'config_cache_enabled' => true,
ConfigAggregator::ENABLE_CACHE => true,
];

View file

@ -3,12 +3,9 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\CLI;
use function Shlinkio\Shlink\Common\env;
return [
'cli' => [
'locale' => env('CLI_LOCALE', 'en'),
'commands' => [
Command\ShortUrl\GenerateShortUrlCommand::NAME => Command\ShortUrl\GenerateShortUrlCommand::class,
Command\ShortUrl\ResolveUrlCommand::NAME => Command\ShortUrl\ResolveUrlCommand::class,

View file

@ -10,8 +10,8 @@ use Shlinkio\Shlink\Core\Service;
use Shlinkio\Shlink\Rest\Service\ApiKeyService;
use Symfony\Component\Console\Application;
use Symfony\Component\Lock;
use Zend\I18n\Translator\Translator;
use Zend\ServiceManager\AbstractFactory\ConfigAbstractFactory;
use Zend\ServiceManager\Factory\InvokableFactory;
return [
@ -29,8 +29,8 @@ return [
Command\Visit\ProcessVisitsCommand::class => ConfigAbstractFactory::class,
Command\Visit\UpdateDbCommand::class => ConfigAbstractFactory::class,
Command\Config\GenerateCharsetCommand::class => ConfigAbstractFactory::class,
Command\Config\GenerateSecretCommand::class => ConfigAbstractFactory::class,
Command\Config\GenerateCharsetCommand::class => InvokableFactory::class,
Command\Config\GenerateSecretCommand::class => InvokableFactory::class,
Command\Api\GenerateKeyCommand::class => ConfigAbstractFactory::class,
Command\Api\DisableKeyCommand::class => ConfigAbstractFactory::class,
@ -44,47 +44,28 @@ return [
],
ConfigAbstractFactory::class => [
Command\ShortUrl\GenerateShortUrlCommand::class => [
Service\UrlShortener::class,
'translator',
'config.url_shortener.domain',
],
Command\ShortUrl\ResolveUrlCommand::class => [Service\UrlShortener::class, 'translator'],
Command\ShortUrl\ListShortUrlsCommand::class => [
Service\ShortUrlService::class,
'translator',
'config.url_shortener.domain',
],
Command\ShortUrl\GetVisitsCommand::class => [Service\VisitsTracker::class, 'translator'],
Command\ShortUrl\GeneratePreviewCommand::class => [
Service\ShortUrlService::class,
PreviewGenerator::class,
'translator',
],
Command\ShortUrl\DeleteShortUrlCommand::class => [
Service\ShortUrl\DeleteShortUrlService::class,
'translator',
],
Command\ShortUrl\GenerateShortUrlCommand::class => [Service\UrlShortener::class, 'config.url_shortener.domain'],
Command\ShortUrl\ResolveUrlCommand::class => [Service\UrlShortener::class],
Command\ShortUrl\ListShortUrlsCommand::class => [Service\ShortUrlService::class, 'config.url_shortener.domain'],
Command\ShortUrl\GetVisitsCommand::class => [Service\VisitsTracker::class],
Command\ShortUrl\GeneratePreviewCommand::class => [Service\ShortUrlService::class, PreviewGenerator::class],
Command\ShortUrl\DeleteShortUrlCommand::class => [Service\ShortUrl\DeleteShortUrlService::class],
Command\Visit\ProcessVisitsCommand::class => [
Service\VisitService::class,
IpLocationResolverInterface::class,
Lock\Factory::class,
'translator',
],
Command\Visit\UpdateDbCommand::class => [DbUpdater::class, 'translator'],
Command\Visit\UpdateDbCommand::class => [DbUpdater::class],
Command\Config\GenerateCharsetCommand::class => ['translator'],
Command\Config\GenerateSecretCommand::class => ['translator'],
Command\Api\GenerateKeyCommand::class => [ApiKeyService::class],
Command\Api\DisableKeyCommand::class => [ApiKeyService::class],
Command\Api\ListKeysCommand::class => [ApiKeyService::class],
Command\Api\GenerateKeyCommand::class => [ApiKeyService::class, 'translator'],
Command\Api\DisableKeyCommand::class => [ApiKeyService::class, 'translator'],
Command\Api\ListKeysCommand::class => [ApiKeyService::class, 'translator'],
Command\Tag\ListTagsCommand::class => [Service\Tag\TagService::class, Translator::class],
Command\Tag\CreateTagCommand::class => [Service\Tag\TagService::class, Translator::class],
Command\Tag\RenameTagCommand::class => [Service\Tag\TagService::class, Translator::class],
Command\Tag\DeleteTagsCommand::class => [Service\Tag\TagService::class, Translator::class],
Command\Tag\ListTagsCommand::class => [Service\Tag\TagService::class],
Command\Tag\CreateTagCommand::class => [Service\Tag\TagService::class],
Command\Tag\RenameTagCommand::class => [Service\Tag\TagService::class],
Command\Tag\DeleteTagsCommand::class => [Service\Tag\TagService::class],
],
];

View file

@ -1,16 +0,0 @@
<?php
declare(strict_types=1);
return [
'translator' => [
'translation_file_patterns' => [
[
'type' => 'gettext',
'base_dir' => __DIR__ . '/../lang',
'pattern' => '%s.mo',
],
],
],
];

Binary file not shown.

View file

@ -1,403 +0,0 @@
msgid ""
msgstr ""
"Project-Id-Version: Shlink 1.0\n"
"POT-Creation-Date: 2018-11-17 14:29+0100\n"
"PO-Revision-Date: 2018-11-17 14:29+0100\n"
"Last-Translator: Alejandro Celaya <alejandro@alejandrocelaya.com>\n"
"Language-Team: \n"
"Language: es_ES\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.0.6\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: translate;translatePlural\n"
"X-Poedit-SearchPath-0: src\n"
"X-Poedit-SearchPath-1: config\n"
msgid "Disables an API key."
msgstr "Desahbilita una clave de API."
msgid "The API key to disable"
msgstr "La clave de API a deshabilitar"
#, php-format
msgid "API key \"%s\" properly disabled"
msgstr "Clave de API \"%s\" deshabilitada correctamente"
#, php-format
msgid "API key \"%s\" does not exist."
msgstr "La clave de API \"%s\" no existe."
msgid "Generates a new valid API key."
msgstr "Genera una nueva clave de API válida."
msgid "The date in which the API key should expire. Use any valid PHP format."
msgstr ""
"La fecha en la que la clave de API debe expirar. Utiliza cualquier valor "
"válido en PHP."
#, php-format
msgid "Generated API key: \"%s\""
msgstr "Generada clave de API. \"%s\""
msgid "Lists all the available API keys."
msgstr "Lista todas las claves de API disponibles."
msgid "Tells if only enabled API keys should be returned."
msgstr "Define si sólo las claves de API habilitadas deben ser devueltas."
msgid "Key"
msgstr "Clave"
msgid "Is enabled"
msgstr "Está habilitada"
msgid "Expiration date"
msgstr "Fecha de caducidad"
#, php-format
msgid ""
"Generates a character set sample just by shuffling the default one, \"%s\". "
"Then it can be set in the SHORTCODE_CHARS environment variable"
msgstr ""
"Genera un grupo de caracteres simplemente mexclando el grupo por defecto \"%s"
"\". Después puede ser utilizado en la variable de entrono SHORTCODE_CHARS"
#, php-format
msgid "Character set: \"%s\""
msgstr "Grupo de caracteres: \"%s\""
msgid ""
"Generates a random secret string that can be used for JWT token encryption"
msgstr ""
"Genera una cadena de caracteres aleatoria que puede ser usada para cifrar "
"tokens JWT"
#, php-format
msgid "Secret key: \"%s\""
msgstr "Clave secreta: \"%s\""
msgid "Deletes a short URL"
msgstr "Elimina una URL"
msgid "The short code for the short URL to be deleted"
msgstr "El código corto de la URL corta a eliminar"
msgid ""
"Ignores the safety visits threshold check, which could make short URLs with "
"many visits to be accidentally deleted"
msgstr ""
"Ignora el límite de seguridad de visitas, pudiendo resultar en el borrado "
"accidental de URLs con muchas visitas"
#, php-format
msgid "Provided short code \"%s\" could not be found."
msgstr "El código corto proporcionado \"%s\" no ha podido ser encontrado."
#, php-format
msgid ""
"It was not possible to delete the short URL with short code \"%s\" because "
"it has more than %s visits."
msgstr ""
"No se pudo eliminar la URL acortada con código corto \"%s\" porque tiene más "
"de %s visitas."
msgid "Do you want to delete it anyway?"
msgstr "¿Aún así quieres eliminarla?"
msgid "Short URL was not deleted."
msgstr "La URL corta no ha sido eliminada."
#, php-format
msgid "Short URL with short code \"%s\" successfully deleted."
msgstr "La URL acortada con el código corto \"%s\" eliminada correctamente."
msgid ""
"Processes and generates the previews for every URL, improving performance "
"for later web requests."
msgstr ""
"Procesa y genera las vistas previas para cada URL, mejorando el rendimiento "
"para peticiones web posteriores."
msgid "Finished processing all URLs"
msgstr "Finalizado el procesado de todas las URLs"
#, php-format
msgid "Processing URL %s..."
msgstr "Procesando URL %s..."
msgid " <info>Success!</info>"
msgstr " <info>¡Correcto!</info>"
msgid "Error"
msgstr "Error"
msgid "Generates a short URL for provided long URL and returns it"
msgstr "Genera una URL corta para la URL larga proporcionada y la devuelve"
msgid "The long URL to parse"
msgstr "La URL larga a procesar"
msgid "Tags to apply to the new short URL"
msgstr "Etiquetas a aplicar a la nueva URL acortada"
msgid ""
"The date from which this short URL will be valid. If someone tries to access "
"it before this date, it will not be found."
msgstr ""
"La fecha desde la cual será válida esta URL acortada. Si alguien intenta "
"acceder a ella antes de esta fecha, no será encontrada."
msgid ""
"The date until which this short URL will be valid. If someone tries to "
"access it after this date, it will not be found."
msgstr ""
"La fecha hasta la cual será válida está URL acortada. Si alguien intenta "
"acceder a ella después de esta fecha, no será encontrada."
msgid "If provided, this slug will be used instead of generating a short code"
msgstr ""
"Si se proporciona, este slug será usado en vez de generar un código corto"
msgid "This will limit the number of visits for this short URL."
msgstr "Esto limitará el número de visitas a esta URL acortada."
#, fuzzy
#| msgid "A long URL was not provided. Which URL do you want to shorten?:"
msgid "A long URL was not provided. Which URL do you want to be shortened?"
msgstr "No se ha proporcionado una URL larga. ¿Qué URL deseas acortar?"
msgid "A URL was not provided!"
msgstr "¡No se ha proporcionado una URL!"
msgid "Processed long URL:"
msgstr "URL larga procesada:"
msgid "Generated short URL:"
msgstr "URL corta generada:"
#, php-format
msgid "Provided URL \"%s\" is invalid. Try with a different one."
msgstr "La URL proporcionada \"%s\" e inválida. Prueba con una diferente."
#, php-format
msgid ""
"Provided slug \"%s\" is already in use by another URL. Try with a different "
"one."
msgstr ""
"El slug proporcionado \"%s\" ya está siendo usado para otra URL. Prueba con "
"uno diferente."
msgid "Returns the detailed visits information for provided short code"
msgstr ""
"Devuelve la información detallada de visitas para el código corto "
"proporcionado"
msgid "The short code which visits we want to get"
msgstr "El código corto del cual queremos obtener las visitas"
msgid "Allows to filter visits, returning only those older than start date"
msgstr ""
"Permite filtrar las visitas, devolviendo sólo aquellas más antiguas que "
"startDate"
msgid "Allows to filter visits, returning only those newer than end date"
msgstr ""
"Permite filtrar las visitas, devolviendo sólo aquellas más nuevas que endDate"
msgid "A short code was not provided. Which short code do you want to use?"
msgstr "No se proporcionó un código corto. ¿Qué código corto deseas usar?"
msgid "Referer"
msgstr "Origen"
msgid "Date"
msgstr "Fecha"
msgid "User agent"
msgstr "Agente de usuario"
msgid "Country"
msgstr "País"
msgid "List all short URLs"
msgstr "Listar todas las URLs cortas"
#, php-format
msgid "The first page to list (%s items per page)"
msgstr "La primera página a listar (%s elementos por página)"
msgid ""
"A query used to filter results by searching for it on the longUrl and "
"shortCode fields"
msgstr ""
"Una consulta usada para filtrar el resultado buscándola en los campos "
"longUrl y shortCode"
msgid "A comma-separated list of tags to filter results"
msgstr "Una lista de etiquetas separadas por coma para filtrar el resultado"
msgid ""
"The field from which we want to order by. Pass ASC or DESC separated by a "
"comma"
msgstr ""
"El campo por el cual queremos ordernar. Pasa ASC o DESC separado por una coma"
msgid "Whether to display the tags or not"
msgstr "Si se desea mostrar las etiquetas o no"
msgid "Short code"
msgstr "Código corto"
msgid "Short URL"
msgstr "URL corta"
msgid "Long URL"
msgstr "URL larga"
msgid "Date created"
msgstr "Fecha de creación"
msgid "Visits count"
msgstr "Número de visitas"
msgid "Tags"
msgstr "Etiquetas"
msgid "Short URLs properly listed"
msgstr "URLs cortas listadas correctamente"
msgid "Continue with page"
msgstr "Continuar con la página"
msgid "Returns the long URL behind a short code"
msgstr "Devuelve la URL larga detrás de un código corto"
msgid "The short code to parse"
msgstr "El código corto a convertir"
msgid "A short code was not provided. Which short code do you want to parse?"
msgstr ""
"No se proporcionó un código corto. ¿Qué código corto quieres convertir?"
msgid "Long URL:"
msgstr "URL larga:"
#, php-format
msgid "Provided short code \"%s\" has an invalid format."
msgstr "El código corto proporcionado \"%s\" tiene un formato inválido."
msgid "Creates one or more tags."
msgstr "Crea una o más etiquetas."
msgid "The name of the tags to create"
msgstr "El nombre de las etiquetas a crear"
msgid "You have to provide at least one tag name"
msgstr "Debes proporcionar al menos un nombre de etiqueta"
msgid "Tags properly created"
msgstr "Etiquetas correctamente creadas"
msgid "Deletes one or more tags."
msgstr "Elimina una o más etiquetas."
msgid "The name of the tags to delete"
msgstr "El nombre de las etiquetas a eliminar"
msgid "Tags properly deleted"
msgstr "Etiquetas correctamente eliminadas"
msgid "Lists existing tags."
msgstr "Lista las etiquetas existentes."
#, fuzzy
msgid "Name"
msgstr "Nombre"
msgid "No tags yet"
msgstr "Aún no hay etiquetas"
msgid "Renames one existing tag."
msgstr "Renombra una etiqueta existente."
msgid "Current name of the tag."
msgstr "Nombre actual de la etiqueta."
msgid "New name of the tag."
msgstr "Nuevo nombre de la etiqueta."
msgid "Tag properly renamed."
msgstr "Etiqueta correctamente renombrada."
#, php-format
msgid "A tag with name \"%s\" was not found"
msgstr "Una etiqueta con nombre \"%s\" no ha sido encontrada"
msgid "Processes visits where location is not set yet"
msgstr "Procesa las visitas donde la localización no ha sido establecida aún"
#, php-format
msgid "There is already an instance of the \"%s\" command in execution"
msgstr "Ya existe una instancia del comando \"%s\" en ejecución"
#, php-format
msgid "Address located at \"%s\""
msgstr "Dirección localizada en \"%s\""
msgid "Finished processing all IPs"
msgstr "Finalizado el procesado de todas las IPs"
msgid "Ignored visit with no IP address"
msgstr "Ignorada visita sin dirección IP"
msgid "Processing IP"
msgstr "Procesando IP"
msgid "Ignored localhost address"
msgstr "Ignorada IP de localhost"
msgid "An error occurred while locating IP. Skipped"
msgstr "Se produjo un error al localizar la IP. Ignorado"
msgid "Updates the GeoLite2 database file used to geolocate IP addresses"
msgstr ""
"Actualiza el fichero de base de datos de GeoLite2 usado para geolocalizar "
"direcciones IP"
msgid ""
"The GeoLite2 database is updated first Tuesday every month, so this command "
"should be ideally run every first Wednesday"
msgstr ""
"La base de datos de GeoLite2 se actualiza el primer Martes de cada mes, por "
"lo que la opción ideal es ejecutar este comando cada primer miércoles de mes"
msgid "GeoLite2 database properly updated"
msgstr "Base de datos de GeoLite2 correctamente actualizada"
msgid "An error occurred while updating GeoLite2 database"
msgstr "Se produjo un error al actualizar la base de datos de GeoLite2"
#~ msgid "IP location resolver limit reached. Waiting %s seconds..."
#~ msgstr "Limite del localizador de IPs alcanzado. Esperando %s segundos..."
#~ msgid "Remote Address"
#~ msgstr "Dirección remota"
#~ msgid "Original URL"
#~ msgstr "URL original"
#~ msgid "You have reached last page"
#~ msgstr "Has alcanzado la última página"
#~ msgid "No URL found for short code \"%s\""
#~ msgstr "No se ha encontrado ninguna URL para el código corto \"%s\""
#~ msgid "Created tags"
#~ msgstr "Etiquetas creadas"
#~ msgid "Deleted tags"
#~ msgstr "Etiquetas eliminadas"

View file

@ -10,7 +10,6 @@ use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Zend\I18n\Translator\TranslatorInterface;
use function sprintf;
class DisableKeyCommand extends Command
@ -21,23 +20,18 @@ class DisableKeyCommand extends Command
* @var ApiKeyServiceInterface
*/
private $apiKeyService;
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(ApiKeyServiceInterface $apiKeyService, TranslatorInterface $translator)
public function __construct(ApiKeyServiceInterface $apiKeyService)
{
$this->apiKeyService = $apiKeyService;
$this->translator = $translator;
parent::__construct();
$this->apiKeyService = $apiKeyService;
}
protected function configure(): void
{
$this->setName(self::NAME)
->setDescription($this->translator->translate('Disables an API key.'))
->addArgument('apiKey', InputArgument::REQUIRED, $this->translator->translate('The API key to disable'));
->setDescription('Disables an API key.')
->addArgument('apiKey', InputArgument::REQUIRED, 'The API key to disable');
}
protected function execute(InputInterface $input, OutputInterface $output): void
@ -47,9 +41,9 @@ class DisableKeyCommand extends Command
try {
$this->apiKeyService->disable($apiKey);
$io->success(sprintf($this->translator->translate('API key "%s" properly disabled'), $apiKey));
$io->success(sprintf('API key "%s" properly disabled', $apiKey));
} catch (InvalidArgumentException $e) {
$io->error(sprintf($this->translator->translate('API key "%s" does not exist.'), $apiKey));
$io->error(sprintf('API key "%s" does not exist.', $apiKey));
}
}
}

View file

@ -10,7 +10,6 @@ use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Zend\I18n\Translator\TranslatorInterface;
use function sprintf;
class GenerateKeyCommand extends Command
@ -21,28 +20,24 @@ class GenerateKeyCommand extends Command
* @var ApiKeyServiceInterface
*/
private $apiKeyService;
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(ApiKeyServiceInterface $apiKeyService, TranslatorInterface $translator)
public function __construct(ApiKeyServiceInterface $apiKeyService)
{
$this->apiKeyService = $apiKeyService;
$this->translator = $translator;
parent::__construct();
}
protected function configure(): void
{
$this->setName(self::NAME)
->setDescription($this->translator->translate('Generates a new valid API key.'))
->addOption(
'expirationDate',
'e',
InputOption::VALUE_OPTIONAL,
$this->translator->translate('The date in which the API key should expire. Use any valid PHP format.')
);
$this
->setName(self::NAME)
->setDescription('Generates a new valid API key.')
->addOption(
'expirationDate',
'e',
InputOption::VALUE_OPTIONAL,
'The date in which the API key should expire. Use any valid PHP format.'
);
}
protected function execute(InputInterface $input, OutputInterface $output): void
@ -50,8 +45,6 @@ class GenerateKeyCommand extends Command
$expirationDate = $input->getOption('expirationDate');
$apiKey = $this->apiKeyService->create(isset($expirationDate) ? Chronos::parse($expirationDate) : null);
(new SymfonyStyle($input, $output))->success(
sprintf($this->translator->translate('Generated API key: "%s"'), $apiKey)
);
(new SymfonyStyle($input, $output))->success(sprintf('Generated API key: "%s"', $apiKey));
}
}

View file

@ -10,7 +10,6 @@ use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Zend\I18n\Translator\TranslatorInterface;
use function array_filter;
use function array_map;
use function sprintf;
@ -27,28 +26,24 @@ class ListKeysCommand extends Command
* @var ApiKeyServiceInterface
*/
private $apiKeyService;
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(ApiKeyServiceInterface $apiKeyService, TranslatorInterface $translator)
public function __construct(ApiKeyServiceInterface $apiKeyService)
{
$this->apiKeyService = $apiKeyService;
$this->translator = $translator;
parent::__construct();
$this->apiKeyService = $apiKeyService;
}
protected function configure(): void
{
$this->setName(self::NAME)
->setDescription($this->translator->translate('Lists all the available API keys.'))
->addOption(
'enabledOnly',
null,
InputOption::VALUE_NONE,
$this->translator->translate('Tells if only enabled API keys should be returned.')
);
$this
->setName(self::NAME)
->setDescription('Lists all the available API keys.')
->addOption(
'enabledOnly',
'e',
InputOption::VALUE_NONE,
'Tells if only enabled API keys should be returned.'
);
}
protected function execute(InputInterface $input, OutputInterface $output): void
@ -70,9 +65,9 @@ class ListKeysCommand extends Command
}, $this->apiKeyService->listKeys($enabledOnly));
$io->table(array_filter([
$this->translator->translate('Key'),
! $enabledOnly ? $this->translator->translate('Is enabled') : null,
$this->translator->translate('Expiration date'),
'Key',
! $enabledOnly ? 'Is enabled' : null,
'Expiration date',
]), $rows);
}

View file

@ -8,7 +8,6 @@ use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Zend\I18n\Translator\TranslatorInterface;
use function sprintf;
use function str_shuffle;
@ -16,31 +15,20 @@ class GenerateCharsetCommand extends Command
{
public const NAME = 'config:generate-charset';
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(TranslatorInterface $translator)
{
$this->translator = $translator;
parent::__construct();
}
protected function configure(): void
{
$this->setName(self::NAME)
->setDescription(sprintf($this->translator->translate(
'Generates a character set sample just by shuffling the default one, "%s". '
. 'Then it can be set in the SHORTCODE_CHARS environment variable'
), UrlShortener::DEFAULT_CHARS));
$this
->setName(self::NAME)
->setDescription(sprintf(
'Generates a character set sample just by shuffling the default one, "%s". '
. 'Then it can be set in the SHORTCODE_CHARS environment variable',
UrlShortener::DEFAULT_CHARS
));
}
protected function execute(InputInterface $input, OutputInterface $output): void
{
$charSet = str_shuffle(UrlShortener::DEFAULT_CHARS);
(new SymfonyStyle($input, $output))->success(
sprintf($this->translator->translate('Character set: "%s"'), $charSet)
);
(new SymfonyStyle($input, $output))->success(sprintf('Character set: "%s"', $charSet));
}
}

View file

@ -8,7 +8,6 @@ use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Zend\I18n\Translator\TranslatorInterface;
use function sprintf;
class GenerateSecretCommand extends Command
@ -17,30 +16,16 @@ class GenerateSecretCommand extends Command
public const NAME = 'config:generate-secret';
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(TranslatorInterface $translator)
{
$this->translator = $translator;
parent::__construct();
}
protected function configure(): void
{
$this->setName(self::NAME)
->setDescription($this->translator->translate(
'Generates a random secret string that can be used for JWT token encryption'
));
$this
->setName(self::NAME)
->setDescription('[DEPRECATED] Generates a random secret string that can be used for JWT token encryption');
}
protected function execute(InputInterface $input, OutputInterface $output): void
{
$secret = $this->generateRandomString(32);
(new SymfonyStyle($input, $output))->success(
sprintf($this->translator->translate('Secret key: "%s"'), $secret)
);
(new SymfonyStyle($input, $output))->success(sprintf('Secret key: "%s"', $secret));
}
}

View file

@ -11,7 +11,6 @@ use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Zend\I18n\Translator\TranslatorInterface;
use function sprintf;
class DeleteShortUrlCommand extends Command
@ -23,16 +22,11 @@ class DeleteShortUrlCommand extends Command
* @var DeleteShortUrlServiceInterface
*/
private $deleteShortUrlService;
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(DeleteShortUrlServiceInterface $deleteShortUrlService, TranslatorInterface $translator)
public function __construct(DeleteShortUrlServiceInterface $deleteShortUrlService)
{
$this->deleteShortUrlService = $deleteShortUrlService;
$this->translator = $translator;
parent::__construct();
$this->deleteShortUrlService = $deleteShortUrlService;
}
protected function configure(): void
@ -40,22 +34,14 @@ class DeleteShortUrlCommand extends Command
$this
->setName(self::NAME)
->setAliases(self::ALIASES)
->setDescription(
$this->translator->translate('Deletes a short URL')
)
->addArgument(
'shortCode',
InputArgument::REQUIRED,
$this->translator->translate('The short code for the short URL to be deleted')
)
->setDescription('Deletes a short URL')
->addArgument('shortCode', InputArgument::REQUIRED, 'The short code for the short URL to be deleted')
->addOption(
'ignore-threshold',
'i',
InputOption::VALUE_NONE,
$this->translator->translate(
'Ignores the safety visits threshold check, which could make short URLs with many visits to be '
. 'accidentally deleted'
)
'Ignores the safety visits threshold check, which could make short URLs with many visits to be '
. 'accidentally deleted'
);
}
@ -68,9 +54,7 @@ class DeleteShortUrlCommand extends Command
try {
$this->runDelete($io, $shortCode, $ignoreThreshold);
} catch (Exception\InvalidShortCodeException $e) {
$io->error(
sprintf($this->translator->translate('Provided short code "%s" could not be found.'), $shortCode)
);
$io->error(sprintf('Provided short code "%s" could not be found.', $shortCode));
} catch (Exception\DeleteShortUrlException $e) {
$this->retry($io, $shortCode, $e);
}
@ -78,25 +62,24 @@ class DeleteShortUrlCommand extends Command
private function retry(SymfonyStyle $io, string $shortCode, Exception\DeleteShortUrlException $e): void
{
$warningMsg = sprintf($this->translator->translate(
'It was not possible to delete the short URL with short code "%s" because it has more than %s visits.'
), $shortCode, $e->getVisitsThreshold());
$warningMsg = sprintf(
'It was not possible to delete the short URL with short code "%s" because it has more than %s visits.',
$shortCode,
$e->getVisitsThreshold()
);
$io->writeln('<bg=yellow>' . $warningMsg . '</>');
$forceDelete = $io->confirm($this->translator->translate('Do you want to delete it anyway?'), false);
$forceDelete = $io->confirm('Do you want to delete it anyway?', false);
if ($forceDelete) {
$this->runDelete($io, $shortCode, true);
} else {
$io->warning($this->translator->translate('Short URL was not deleted.'));
$io->warning('Short URL was not deleted.');
}
}
private function runDelete(SymfonyStyle $io, string $shortCode, bool $ignoreThreshold): void
{
$this->deleteShortUrlService->deleteByShortCode($shortCode, $ignoreThreshold);
$io->success(sprintf(
$this->translator->translate('Short URL with short code "%s" successfully deleted.'),
$shortCode
));
$io->success(sprintf('Short URL with short code "%s" successfully deleted.', $shortCode));
}
}

View file

@ -10,7 +10,6 @@ use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Zend\I18n\Translator\TranslatorInterface;
use function sprintf;
class GeneratePreviewCommand extends Command
@ -22,24 +21,16 @@ class GeneratePreviewCommand extends Command
* @var PreviewGeneratorInterface
*/
private $previewGenerator;
/**
* @var TranslatorInterface
*/
private $translator;
/**
* @var ShortUrlServiceInterface
*/
private $shortUrlService;
public function __construct(
ShortUrlServiceInterface $shortUrlService,
PreviewGeneratorInterface $previewGenerator,
TranslatorInterface $translator
) {
public function __construct(ShortUrlServiceInterface $shortUrlService, PreviewGeneratorInterface $previewGenerator)
{
parent::__construct();
$this->shortUrlService = $shortUrlService;
$this->previewGenerator = $previewGenerator;
$this->translator = $translator;
parent::__construct(null);
}
protected function configure(): void
@ -48,9 +39,7 @@ class GeneratePreviewCommand extends Command
->setName(self::NAME)
->setAliases(self::ALIASES)
->setDescription(
$this->translator->translate(
'Processes and generates the previews for every URL, improving performance for later web requests.'
)
'Processes and generates the previews for every URL, improving performance for later web requests.'
);
}
@ -66,17 +55,17 @@ class GeneratePreviewCommand extends Command
}
} while ($page <= $shortUrls->count());
(new SymfonyStyle($input, $output))->success($this->translator->translate('Finished processing all URLs'));
(new SymfonyStyle($input, $output))->success('Finished processing all URLs');
}
private function processUrl($url, OutputInterface $output): void
{
try {
$output->write(sprintf($this->translator->translate('Processing URL %s...'), $url));
$output->write(sprintf('Processing URL %s...', $url));
$this->previewGenerator->generatePreview($url);
$output->writeln($this->translator->translate(' <info>Success!</info>'));
$output->writeln(' <info>Success!</info>');
} catch (PreviewGenerationException $e) {
$output->writeln(' <error>' . $this->translator->translate('Error') . '</error>');
$output->writeln(' <error>Error</error>');
if ($output->isVerbose()) {
$this->getApplication()->renderException($e, $output);
}

View file

@ -15,7 +15,6 @@ use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Zend\Diactoros\Uri;
use Zend\I18n\Translator\TranslatorInterface;
use function array_merge;
use function explode;
use function sprintf;
@ -35,20 +34,12 @@ class GenerateShortUrlCommand extends Command
* @var array
*/
private $domainConfig;
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(
UrlShortenerInterface $urlShortener,
TranslatorInterface $translator,
array $domainConfig
) {
public function __construct(UrlShortenerInterface $urlShortener, array $domainConfig)
{
parent::__construct();
$this->urlShortener = $urlShortener;
$this->translator = $translator;
$this->domainConfig = $domainConfig;
parent::__construct(null);
}
protected function configure(): void
@ -56,30 +47,40 @@ class GenerateShortUrlCommand extends Command
$this
->setName(self::NAME)
->setAliases(self::ALIASES)
->setDescription(
$this->translator->translate('Generates a short URL for provided long URL and returns it')
)
->addArgument('longUrl', InputArgument::REQUIRED, $this->translator->translate('The long URL to parse'))
->setDescription('Generates a short URL for provided long URL and returns it')
->addArgument('longUrl', InputArgument::REQUIRED, 'The long URL to parse')
->addOption(
'tags',
't',
InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED,
$this->translator->translate('Tags to apply to the new short URL')
'Tags to apply to the new short URL'
)
->addOption('validSince', 's', InputOption::VALUE_REQUIRED, $this->translator->translate(
->addOption(
'validSince',
's',
InputOption::VALUE_REQUIRED,
'The date from which this short URL will be valid. '
. 'If someone tries to access it before this date, it will not be found.'
))
->addOption('validUntil', 'u', InputOption::VALUE_REQUIRED, $this->translator->translate(
)
->addOption(
'validUntil',
'u',
InputOption::VALUE_REQUIRED,
'The date until which this short URL will be valid. '
. 'If someone tries to access it after this date, it will not be found.'
))
->addOption('customSlug', 'c', InputOption::VALUE_REQUIRED, $this->translator->translate(
)
->addOption(
'customSlug',
'c',
InputOption::VALUE_REQUIRED,
'If provided, this slug will be used instead of generating a short code'
))
->addOption('maxVisits', 'm', InputOption::VALUE_REQUIRED, $this->translator->translate(
)
->addOption(
'maxVisits',
'm',
InputOption::VALUE_REQUIRED,
'This will limit the number of visits for this short URL.'
));
);
}
protected function interact(InputInterface $input, OutputInterface $output): void
@ -90,9 +91,7 @@ class GenerateShortUrlCommand extends Command
return;
}
$longUrl = $io->ask(
$this->translator->translate('A long URL was not provided. Which URL do you want to be shortened?')
);
$longUrl = $io->ask('A long URL was not provided. Which URL do you want to be shortened?');
if (! empty($longUrl)) {
$input->setArgument('longUrl', $longUrl);
}
@ -103,7 +102,7 @@ class GenerateShortUrlCommand extends Command
$io = new SymfonyStyle($input, $output);
$longUrl = $input->getArgument('longUrl');
if (empty($longUrl)) {
$io->error($this->translator->translate('A URL was not provided!'));
$io->error('A URL was not provided!');
return;
}
@ -129,21 +128,15 @@ class GenerateShortUrlCommand extends Command
$shortUrl = $this->buildShortUrl($this->domainConfig, $shortCode);
$io->writeln([
sprintf('%s <info>%s</info>', $this->translator->translate('Processed long URL:'), $longUrl),
sprintf('%s <info>%s</info>', $this->translator->translate('Generated short URL:'), $shortUrl),
sprintf('Processed long URL: <info>%s</info>', $longUrl),
sprintf('Generated short URL: <info>%s</info>', $shortUrl),
]);
} catch (InvalidUrlException $e) {
$io->error(sprintf(
$this->translator->translate('Provided URL "%s" is invalid. Try with a different one.'),
$longUrl
));
$io->error(sprintf('Provided URL "%s" is invalid. Try with a different one.', $longUrl));
} catch (NonUniqueSlugException $e) {
$io->error(sprintf(
$this->translator->translate(
'Provided slug "%s" is already in use by another URL. Try with a different one.'
),
$customSlug
));
$io->error(
sprintf('Provided slug "%s" is already in use by another URL. Try with a different one.', $customSlug)
);
}
}

View file

@ -13,7 +13,6 @@ use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Zend\I18n\Translator\TranslatorInterface;
use function array_map;
use function Functional\select_keys;
@ -26,15 +25,10 @@ class GetVisitsCommand extends Command
* @var VisitsTrackerInterface
*/
private $visitsTracker;
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(VisitsTrackerInterface $visitsTracker, TranslatorInterface $translator)
public function __construct(VisitsTrackerInterface $visitsTracker)
{
$this->visitsTracker = $visitsTracker;
$this->translator = $translator;
parent::__construct();
}
@ -43,25 +37,19 @@ class GetVisitsCommand extends Command
$this
->setName(self::NAME)
->setAliases(self::ALIASES)
->setDescription(
$this->translator->translate('Returns the detailed visits information for provided short code')
)
->addArgument(
'shortCode',
InputArgument::REQUIRED,
$this->translator->translate('The short code which visits we want to get')
)
->setDescription('Returns the detailed visits information for provided short code')
->addArgument('shortCode', InputArgument::REQUIRED, 'The short code which visits we want to get')
->addOption(
'startDate',
's',
InputOption::VALUE_OPTIONAL,
$this->translator->translate('Allows to filter visits, returning only those older than start date')
'Allows to filter visits, returning only those older than start date'
)
->addOption(
'endDate',
'e',
InputOption::VALUE_OPTIONAL,
$this->translator->translate('Allows to filter visits, returning only those newer than end date')
'Allows to filter visits, returning only those newer than end date'
);
}
@ -73,9 +61,7 @@ class GetVisitsCommand extends Command
}
$io = new SymfonyStyle($input, $output);
$shortCode = $io->ask(
$this->translator->translate('A short code was not provided. Which short code do you want to use?')
);
$shortCode = $io->ask('A short code was not provided. Which short code do you want to use?');
if (! empty($shortCode)) {
$input->setArgument('shortCode', $shortCode);
}
@ -94,12 +80,7 @@ class GetVisitsCommand extends Command
$rowData['country'] = $visit->getVisitLocation()->getCountryName();
return select_keys($rowData, ['referer', 'date', 'userAgent', 'country']);
}, $visits);
$io->table([
$this->translator->translate('Referer'),
$this->translator->translate('Date'),
$this->translator->translate('User agent'),
$this->translator->translate('Country'),
], $rows);
$io->table(['Referer', 'Date', 'User agent', 'Country'], $rows);
}
private function getDateOption(InputInterface $input, $key)

View file

@ -12,7 +12,6 @@ use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Zend\I18n\Translator\TranslatorInterface;
use function array_values;
use function count;
use function explode;
@ -30,23 +29,15 @@ class ListShortUrlsCommand extends Command
* @var ShortUrlServiceInterface
*/
private $shortUrlService;
/**
* @var TranslatorInterface
*/
private $translator;
/**
* @var array
*/
private $domainConfig;
public function __construct(
ShortUrlServiceInterface $shortUrlService,
TranslatorInterface $translator,
array $domainConfig
) {
$this->shortUrlService = $shortUrlService;
$this->translator = $translator;
public function __construct(ShortUrlServiceInterface $shortUrlService, array $domainConfig)
{
parent::__construct();
$this->shortUrlService = $shortUrlService;
$this->domainConfig = $domainConfig;
}
@ -55,45 +46,33 @@ class ListShortUrlsCommand extends Command
$this
->setName(self::NAME)
->setAliases(self::ALIASES)
->setDescription($this->translator->translate('List all short URLs'))
->setDescription('List all short URLs')
->addOption(
'page',
'p',
InputOption::VALUE_OPTIONAL,
sprintf(
$this->translator->translate('The first page to list (%s items per page)'),
PaginableRepositoryAdapter::ITEMS_PER_PAGE
),
sprintf('The first page to list (%s items per page)', PaginableRepositoryAdapter::ITEMS_PER_PAGE),
'1'
)
->addOption(
'searchTerm',
's',
InputOption::VALUE_OPTIONAL,
$this->translator->translate(
'A query used to filter results by searching for it on the longUrl and shortCode fields'
)
'A query used to filter results by searching for it on the longUrl and shortCode fields'
)
->addOption(
'tags',
't',
InputOption::VALUE_OPTIONAL,
$this->translator->translate('A comma-separated list of tags to filter results')
'A comma-separated list of tags to filter results'
)
->addOption(
'orderBy',
'o',
InputOption::VALUE_OPTIONAL,
$this->translator->translate(
'The field from which we want to order by. Pass ASC or DESC separated by a comma'
)
'The field from which we want to order by. Pass ASC or DESC separated by a comma'
)
->addOption(
'showTags',
null,
InputOption::VALUE_NONE,
$this->translator->translate('Whether to display the tags or not')
);
->addOption('showTags', null, InputOption::VALUE_NONE, 'Whether to display the tags or not');
}
protected function execute(InputInterface $input, OutputInterface $output): void
@ -110,15 +89,9 @@ class ListShortUrlsCommand extends Command
$result = $this->shortUrlService->listShortUrls($page, $searchTerm, $tags, $this->processOrderBy($input));
$page++;
$headers = [
$this->translator->translate('Short code'),
$this->translator->translate('Short URL'),
$this->translator->translate('Long URL'),
$this->translator->translate('Date created'),
$this->translator->translate('Visits count'),
];
$headers = ['Short code', 'Short URL', 'Long URL', 'Date created', 'Visits count'];
if ($showTags) {
$headers[] = $this->translator->translate('Tags');
$headers[] = 'Tags';
}
$rows = [];
@ -137,12 +110,9 @@ class ListShortUrlsCommand extends Command
if ($this->isLastPage($result)) {
$continue = false;
$io->success($this->translator->translate('Short URLs properly listed'));
$io->success('Short URLs properly listed');
} else {
$continue = $io->confirm(
sprintf($this->translator->translate('Continue with page') . ' <options=bold>%s</>?', $page),
false
);
$continue = $io->confirm(sprintf('Continue with page <options=bold>%s</>?', $page), false);
}
} while ($continue);
}

View file

@ -11,7 +11,6 @@ use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Zend\I18n\Translator\TranslatorInterface;
use function sprintf;
class ResolveUrlCommand extends Command
@ -23,16 +22,11 @@ class ResolveUrlCommand extends Command
* @var UrlShortenerInterface
*/
private $urlShortener;
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(UrlShortenerInterface $urlShortener, TranslatorInterface $translator)
public function __construct(UrlShortenerInterface $urlShortener)
{
parent::__construct();
$this->urlShortener = $urlShortener;
$this->translator = $translator;
parent::__construct(null);
}
protected function configure(): void
@ -40,12 +34,8 @@ class ResolveUrlCommand extends Command
$this
->setName(self::NAME)
->setAliases(self::ALIASES)
->setDescription($this->translator->translate('Returns the long URL behind a short code'))
->addArgument(
'shortCode',
InputArgument::REQUIRED,
$this->translator->translate('The short code to parse')
);
->setDescription('Returns the long URL behind a short code')
->addArgument('shortCode', InputArgument::REQUIRED, 'The short code to parse');
}
protected function interact(InputInterface $input, OutputInterface $output): void
@ -56,9 +46,7 @@ class ResolveUrlCommand extends Command
}
$io = new SymfonyStyle($input, $output);
$shortCode = $io->ask(
$this->translator->translate('A short code was not provided. Which short code do you want to parse?')
);
$shortCode = $io->ask('A short code was not provided. Which short code do you want to parse?');
if (! empty($shortCode)) {
$input->setArgument('shortCode', $shortCode);
}
@ -71,17 +59,11 @@ class ResolveUrlCommand extends Command
try {
$url = $this->urlShortener->shortCodeToUrl($shortCode);
$output->writeln(
sprintf('%s <info>%s</info>', $this->translator->translate('Long URL:'), $url->getLongUrl())
);
$output->writeln(sprintf('Long URL: <info>%s</info>', $url->getLongUrl()));
} catch (InvalidShortCodeException $e) {
$io->error(
sprintf($this->translator->translate('Provided short code "%s" has an invalid format.'), $shortCode)
);
$io->error(sprintf('Provided short code "%s" has an invalid format.', $shortCode));
} catch (EntityDoesNotExistException $e) {
$io->error(
sprintf($this->translator->translate('Provided short code "%s" could not be found.'), $shortCode)
);
$io->error(sprintf('Provided short code "%s" could not be found.', $shortCode));
}
}
}

View file

@ -9,7 +9,6 @@ use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Zend\I18n\Translator\TranslatorInterface;
class CreateTagCommand extends Command
{
@ -19,28 +18,23 @@ class CreateTagCommand extends Command
* @var TagServiceInterface
*/
private $tagService;
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(TagServiceInterface $tagService, TranslatorInterface $translator)
public function __construct(TagServiceInterface $tagService)
{
$this->tagService = $tagService;
$this->translator = $translator;
parent::__construct();
$this->tagService = $tagService;
}
protected function configure(): void
{
$this
->setName(self::NAME)
->setDescription($this->translator->translate('Creates one or more tags.'))
->setDescription('Creates one or more tags.')
->addOption(
'name',
't',
InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
$this->translator->translate('The name of the tags to create')
'The name of the tags to create'
);
}
@ -50,11 +44,11 @@ class CreateTagCommand extends Command
$tagNames = $input->getOption('name');
if (empty($tagNames)) {
$io->warning($this->translator->translate('You have to provide at least one tag name'));
$io->warning('You have to provide at least one tag name');
return;
}
$this->tagService->createTags($tagNames);
$io->success($this->translator->translate('Tags properly created'));
$io->success('Tags properly created');
}
}

View file

@ -9,7 +9,6 @@ use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Zend\I18n\Translator\TranslatorInterface;
class DeleteTagsCommand extends Command
{
@ -19,28 +18,23 @@ class DeleteTagsCommand extends Command
* @var TagServiceInterface
*/
private $tagService;
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(TagServiceInterface $tagService, TranslatorInterface $translator)
public function __construct(TagServiceInterface $tagService)
{
$this->tagService = $tagService;
$this->translator = $translator;
parent::__construct();
$this->tagService = $tagService;
}
protected function configure(): void
{
$this
->setName(self::NAME)
->setDescription($this->translator->translate('Deletes one or more tags.'))
->setDescription('Deletes one or more tags.')
->addOption(
'name',
't',
InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
$this->translator->translate('The name of the tags to delete')
'The name of the tags to delete'
);
}
@ -50,11 +44,11 @@ class DeleteTagsCommand extends Command
$tagNames = $input->getOption('name');
if (empty($tagNames)) {
$io->warning($this->translator->translate('You have to provide at least one tag name'));
$io->warning('You have to provide at least one tag name');
return;
}
$this->tagService->deleteTags($tagNames);
$io->success($this->translator->translate('Tags properly deleted'));
$io->success('Tags properly deleted');
}
}

View file

@ -9,7 +9,6 @@ use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Zend\I18n\Translator\TranslatorInterface;
use function Functional\map;
class ListTagsCommand extends Command
@ -20,36 +19,31 @@ class ListTagsCommand extends Command
* @var TagServiceInterface
*/
private $tagService;
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(TagServiceInterface $tagService, TranslatorInterface $translator)
public function __construct(TagServiceInterface $tagService)
{
$this->tagService = $tagService;
$this->translator = $translator;
parent::__construct();
$this->tagService = $tagService;
}
protected function configure(): void
{
$this
->setName(self::NAME)
->setDescription($this->translator->translate('Lists existing tags.'));
->setDescription('Lists existing tags.');
}
protected function execute(InputInterface $input, OutputInterface $output): void
{
$io = new SymfonyStyle($input, $output);
$io->table([$this->translator->translate('Name')], $this->getTagsRows());
$io->table(['Name'], $this->getTagsRows());
}
private function getTagsRows(): array
{
$tags = $this->tagService->listTags();
if (empty($tags)) {
return [[$this->translator->translate('No tags yet')]];
return [['No tags yet']];
}
return map($tags, function (Tag $tag) {

View file

@ -10,7 +10,6 @@ use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Zend\I18n\Translator\TranslatorInterface;
use function sprintf;
class RenameTagCommand extends Command
@ -21,25 +20,20 @@ class RenameTagCommand extends Command
* @var TagServiceInterface
*/
private $tagService;
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(TagServiceInterface $tagService, TranslatorInterface $translator)
public function __construct(TagServiceInterface $tagService)
{
$this->tagService = $tagService;
$this->translator = $translator;
parent::__construct();
$this->tagService = $tagService;
}
protected function configure(): void
{
$this
->setName(self::NAME)
->setDescription($this->translator->translate('Renames one existing tag.'))
->addArgument('oldName', InputArgument::REQUIRED, $this->translator->translate('Current name of the tag.'))
->addArgument('newName', InputArgument::REQUIRED, $this->translator->translate('New name of the tag.'));
->setDescription('Renames one existing tag.')
->addArgument('oldName', InputArgument::REQUIRED, 'Current name of the tag.')
->addArgument('newName', InputArgument::REQUIRED, 'New name of the tag.');
}
protected function execute(InputInterface $input, OutputInterface $output): void
@ -50,9 +44,9 @@ class RenameTagCommand extends Command
try {
$this->tagService->renameTag($oldName, $newName);
$io->success($this->translator->translate('Tag properly renamed.'));
$io->success('Tag properly renamed.');
} catch (EntityDoesNotExistException $e) {
$io->error(sprintf($this->translator->translate('A tag with name "%s" was not found'), $oldName));
$io->error(sprintf('A tag with name "%s" was not found', $oldName));
}
}
}

View file

@ -15,7 +15,6 @@ use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Lock\Factory as Locker;
use Zend\I18n\Translator\TranslatorInterface;
use function sprintf;
class ProcessVisitsCommand extends Command
@ -30,10 +29,6 @@ class ProcessVisitsCommand extends Command
* @var IpLocationResolverInterface
*/
private $ipLocationResolver;
/**
* @var TranslatorInterface
*/
private $translator;
/**
* @var Locker
*/
@ -46,21 +41,19 @@ class ProcessVisitsCommand extends Command
public function __construct(
VisitServiceInterface $visitService,
IpLocationResolverInterface $ipLocationResolver,
Locker $locker,
TranslatorInterface $translator
Locker $locker
) {
parent::__construct();
$this->visitService = $visitService;
$this->ipLocationResolver = $ipLocationResolver;
$this->translator = $translator;
$this->locker = $locker;
parent::__construct();
}
protected function configure(): void
{
$this
->setName(self::NAME)
->setDescription($this->translator->translate('Processes visits where location is not set yet'));
->setDescription('Processes visits where location is not set yet');
}
protected function execute(InputInterface $input, OutputInterface $output): void
@ -70,10 +63,7 @@ class ProcessVisitsCommand extends Command
$lock = $this->locker->createLock(self::NAME);
if (! $lock->acquire()) {
$io->warning(sprintf(
$this->translator->translate('There is already an instance of the "%s" command in execution'),
self::NAME
));
$io->warning(sprintf('There is already an instance of the "%s" command in execution', self::NAME));
return;
}
@ -81,14 +71,11 @@ class ProcessVisitsCommand extends Command
$this->visitService->locateVisits(
[$this, 'getGeolocationDataForVisit'],
function (VisitLocation $location) use ($output) {
$output->writeln(sprintf(
' [<info>' . $this->translator->translate('Address located at "%s"') . '</info>]',
$location->getCountryName()
));
$output->writeln(sprintf(' [<info>Address located at "%s"</info>]', $location->getCountryName()));
}
);
$io->success($this->translator->translate('Finished processing all IPs'));
$io->success('Finished processing all IPs');
} finally {
$lock->release();
}
@ -97,31 +84,24 @@ class ProcessVisitsCommand extends Command
public function getGeolocationDataForVisit(Visit $visit): array
{
if (! $visit->hasRemoteAddr()) {
$this->output->writeln(sprintf(
'<comment>%s</comment>',
$this->translator->translate('Ignored visit with no IP address')
), OutputInterface::VERBOSITY_VERBOSE);
$this->output->writeln(
'<comment>Ignored visit with no IP address</comment>',
OutputInterface::VERBOSITY_VERBOSE
);
throw new IpCannotBeLocatedException('Ignored visit with no IP address');
}
$ipAddr = $visit->getRemoteAddr();
$this->output->write(sprintf('%s <fg=blue>%s</>', $this->translator->translate('Processing IP'), $ipAddr));
$this->output->write(sprintf('Processing IP <fg=blue>%s</>', $ipAddr));
if ($ipAddr === IpAddress::LOCALHOST) {
$this->output->writeln(
sprintf(' [<comment>%s</comment>]', $this->translator->translate('Ignored localhost address'))
);
$this->output->writeln(' [<comment>Ignored localhost address</comment>]');
throw new IpCannotBeLocatedException('Ignored localhost address');
}
try {
return $this->ipLocationResolver->resolveIpLocation($ipAddr);
} catch (WrongIpException $e) {
$this->output->writeln(
sprintf(
' [<fg=red>%s</>]',
$this->translator->translate('An error occurred while locating IP. Skipped')
)
);
$this->output->writeln(' [<fg=red>An error occurred while locating IP. Skipped</>]');
if ($this->output->isVerbose()) {
$this->getApplication()->renderException($e, $this->output);
}

View file

@ -10,7 +10,6 @@ use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Zend\I18n\Translator\TranslatorInterface;
class UpdateDbCommand extends Command
{
@ -20,29 +19,22 @@ class UpdateDbCommand extends Command
* @var DbUpdaterInterface
*/
private $geoLiteDbUpdater;
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(DbUpdaterInterface $geoLiteDbUpdater, TranslatorInterface $translator)
public function __construct(DbUpdaterInterface $geoLiteDbUpdater)
{
$this->geoLiteDbUpdater = $geoLiteDbUpdater;
$this->translator = $translator;
parent::__construct();
$this->geoLiteDbUpdater = $geoLiteDbUpdater;
}
protected function configure(): void
{
$this
->setName(self::NAME)
->setDescription(
$this->translator->translate('Updates the GeoLite2 database file used to geolocate IP addresses')
)
->setHelp($this->translator->translate(
->setDescription('Updates the GeoLite2 database file used to geolocate IP addresses')
->setHelp(
'The GeoLite2 database is updated first Tuesday every month, so this command should be ideally run '
. 'every first Wednesday'
));
);
}
protected function execute(InputInterface $input, OutputInterface $output): void
@ -60,12 +52,12 @@ class UpdateDbCommand extends Command
$progressBar->finish();
$io->writeln('');
$io->success($this->translator->translate('GeoLite2 database properly updated'));
$io->success('GeoLite2 database properly updated');
} catch (RuntimeException $e) {
$progressBar->finish();
$io->writeln('');
$io->error($this->translator->translate('An error occurred while updating GeoLite2 database'));
$io->error('An error occurred while updating GeoLite2 database');
if ($io->isVerbose()) {
$this->getApplication()->renderException($e, $output);
}

View file

@ -10,7 +10,6 @@ use Psr\Container\NotFoundExceptionInterface;
use Shlinkio\Shlink\Core\Options\AppOptions;
use Symfony\Component\Console\Application as CliApp;
use Symfony\Component\Console\CommandLoader\ContainerCommandLoader;
use Zend\I18n\Translator\Translator;
use Zend\ServiceManager\Exception\ServiceNotCreatedException;
use Zend\ServiceManager\Exception\ServiceNotFoundException;
use Zend\ServiceManager\Factory\FactoryInterface;
@ -34,8 +33,6 @@ class ApplicationFactory implements FactoryInterface
{
$config = $container->get('config')['cli'];
$appOptions = $container->get(AppOptions::class);
$translator = $container->get(Translator::class);
$translator->setLocale($config['locale']);
$commands = $config['commands'] ?? [];
$app = new CliApp($appOptions->getName(), $appOptions->getVersion());

View file

@ -10,7 +10,6 @@ use Shlinkio\Shlink\Common\Exception\InvalidArgumentException;
use Shlinkio\Shlink\Rest\Service\ApiKeyService;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Zend\I18n\Translator\Translator;
class DisableKeyCommandTest extends TestCase
{
@ -26,7 +25,7 @@ class DisableKeyCommandTest extends TestCase
public function setUp()
{
$this->apiKeyService = $this->prophesize(ApiKeyService::class);
$command = new DisableKeyCommand($this->apiKeyService->reveal(), Translator::factory([]));
$command = new DisableKeyCommand($this->apiKeyService->reveal());
$app = new Application();
$app->add($command);
$this->commandTester = new CommandTester($command);

View file

@ -12,7 +12,6 @@ use Shlinkio\Shlink\Rest\Entity\ApiKey;
use Shlinkio\Shlink\Rest\Service\ApiKeyService;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Zend\I18n\Translator\Translator;
class GenerateKeyCommandTest extends TestCase
{
@ -28,7 +27,7 @@ class GenerateKeyCommandTest extends TestCase
public function setUp()
{
$this->apiKeyService = $this->prophesize(ApiKeyService::class);
$command = new GenerateKeyCommand($this->apiKeyService->reveal(), Translator::factory([]));
$command = new GenerateKeyCommand($this->apiKeyService->reveal());
$app = new Application();
$app->add($command);
$this->commandTester = new CommandTester($command);

View file

@ -10,7 +10,6 @@ use Shlinkio\Shlink\Rest\Entity\ApiKey;
use Shlinkio\Shlink\Rest\Service\ApiKeyService;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Zend\I18n\Translator\Translator;
class ListKeysCommandTest extends TestCase
{
@ -26,7 +25,7 @@ class ListKeysCommandTest extends TestCase
public function setUp()
{
$this->apiKeyService = $this->prophesize(ApiKeyService::class);
$command = new ListKeysCommand($this->apiKeyService->reveal(), Translator::factory([]));
$command = new ListKeysCommand($this->apiKeyService->reveal());
$app = new Application();
$app->add($command);
$this->commandTester = new CommandTester($command);

View file

@ -7,7 +7,6 @@ use PHPUnit\Framework\TestCase;
use Shlinkio\Shlink\CLI\Command\Config\GenerateCharsetCommand;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Zend\I18n\Translator\Translator;
use function implode;
use function sort;
use function str_split;
@ -21,7 +20,7 @@ class GenerateCharsetCommandTest extends TestCase
public function setUp()
{
$command = new GenerateCharsetCommand(Translator::factory([]));
$command = new GenerateCharsetCommand();
$app = new Application();
$app->add($command);

View file

@ -11,7 +11,6 @@ use Shlinkio\Shlink\Core\Exception;
use Shlinkio\Shlink\Core\Service\ShortUrl\DeleteShortUrlServiceInterface;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Zend\I18n\Translator\Translator;
use function array_pop;
use function sprintf;
@ -30,7 +29,7 @@ class DeleteShortCodeCommandTest extends TestCase
{
$this->service = $this->prophesize(DeleteShortUrlServiceInterface::class);
$command = new DeleteShortUrlCommand($this->service->reveal(), Translator::factory([]));
$command = new DeleteShortUrlCommand($this->service->reveal());
$app = new Application();
$app->add($command);

View file

@ -13,7 +13,6 @@ use Shlinkio\Shlink\Core\Entity\ShortUrl;
use Shlinkio\Shlink\Core\Service\ShortUrlService;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Zend\I18n\Translator\Translator;
use Zend\Paginator\Adapter\ArrayAdapter;
use Zend\Paginator\Paginator;
use function count;
@ -39,11 +38,7 @@ class GeneratePreviewCommandTest extends TestCase
$this->previewGenerator = $this->prophesize(PreviewGenerator::class);
$this->shortUrlService = $this->prophesize(ShortUrlService::class);
$command = new GeneratePreviewCommand(
$this->shortUrlService->reveal(),
$this->previewGenerator->reveal(),
Translator::factory([])
);
$command = new GeneratePreviewCommand($this->shortUrlService->reveal(), $this->previewGenerator->reveal());
$app = new Application();
$app->add($command);

View file

@ -14,7 +14,6 @@ use Shlinkio\Shlink\Core\Exception\InvalidUrlException;
use Shlinkio\Shlink\Core\Service\UrlShortener;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Zend\I18n\Translator\Translator;
class GenerateShortUrlCommandTest extends TestCase
{
@ -30,7 +29,7 @@ class GenerateShortUrlCommandTest extends TestCase
public function setUp()
{
$this->urlShortener = $this->prophesize(UrlShortener::class);
$command = new GenerateShortUrlCommand($this->urlShortener->reveal(), Translator::factory([]), [
$command = new GenerateShortUrlCommand($this->urlShortener->reveal(), [
'schema' => 'http',
'hostname' => 'foo.com',
]);

View file

@ -16,7 +16,6 @@ use Shlinkio\Shlink\Core\Model\Visitor;
use Shlinkio\Shlink\Core\Service\VisitsTrackerInterface;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Zend\I18n\Translator\Translator;
use function strpos;
class GetVisitsCommandTest extends TestCase
@ -33,7 +32,7 @@ class GetVisitsCommandTest extends TestCase
public function setUp()
{
$this->visitsTracker = $this->prophesize(VisitsTrackerInterface::class);
$command = new GetVisitsCommand($this->visitsTracker->reveal(), Translator::factory([]));
$command = new GetVisitsCommand($this->visitsTracker->reveal());
$app = new Application();
$app->add($command);
$this->commandTester = new CommandTester($command);

View file

@ -11,7 +11,6 @@ use Shlinkio\Shlink\Core\Entity\ShortUrl;
use Shlinkio\Shlink\Core\Service\ShortUrlServiceInterface;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Zend\I18n\Translator\Translator;
use Zend\Paginator\Adapter\ArrayAdapter;
use Zend\Paginator\Paginator;
@ -30,7 +29,7 @@ class ListShortUrlsCommandTest extends TestCase
{
$this->shortUrlService = $this->prophesize(ShortUrlServiceInterface::class);
$app = new Application();
$command = new ListShortUrlsCommand($this->shortUrlService->reveal(), Translator::factory([]), []);
$command = new ListShortUrlsCommand($this->shortUrlService->reveal(), []);
$app->add($command);
$this->commandTester = new CommandTester($command);
}

View file

@ -12,7 +12,6 @@ use Shlinkio\Shlink\Core\Exception\InvalidShortCodeException;
use Shlinkio\Shlink\Core\Service\UrlShortener;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Zend\I18n\Translator\Translator;
use const PHP_EOL;
class ResolveUrlCommandTest extends TestCase
@ -29,7 +28,7 @@ class ResolveUrlCommandTest extends TestCase
public function setUp()
{
$this->urlShortener = $this->prophesize(UrlShortener::class);
$command = new ResolveUrlCommand($this->urlShortener->reveal(), Translator::factory([]));
$command = new ResolveUrlCommand($this->urlShortener->reveal());
$app = new Application();
$app->add($command);

View file

@ -11,7 +11,6 @@ use Shlinkio\Shlink\CLI\Command\Tag\CreateTagCommand;
use Shlinkio\Shlink\Core\Service\Tag\TagServiceInterface;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Zend\I18n\Translator\Translator;
class CreateTagCommandTest extends TestCase
{
@ -28,7 +27,7 @@ class CreateTagCommandTest extends TestCase
{
$this->tagService = $this->prophesize(TagServiceInterface::class);
$command = new CreateTagCommand($this->tagService->reveal(), Translator::factory([]));
$command = new CreateTagCommand($this->tagService->reveal());
$app = new Application();
$app->add($command);

View file

@ -10,7 +10,6 @@ use Shlinkio\Shlink\CLI\Command\Tag\DeleteTagsCommand;
use Shlinkio\Shlink\Core\Service\Tag\TagServiceInterface;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Zend\I18n\Translator\Translator;
class DeleteTagsCommandTest extends TestCase
{
@ -31,7 +30,7 @@ class DeleteTagsCommandTest extends TestCase
{
$this->tagService = $this->prophesize(TagServiceInterface::class);
$command = new DeleteTagsCommand($this->tagService->reveal(), Translator::factory([]));
$command = new DeleteTagsCommand($this->tagService->reveal());
$app = new Application();
$app->add($command);

View file

@ -11,7 +11,6 @@ use Shlinkio\Shlink\Core\Entity\Tag;
use Shlinkio\Shlink\Core\Service\Tag\TagServiceInterface;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Zend\I18n\Translator\Translator;
class ListTagsCommandTest extends TestCase
{
@ -32,7 +31,7 @@ class ListTagsCommandTest extends TestCase
{
$this->tagService = $this->prophesize(TagServiceInterface::class);
$command = new ListTagsCommand($this->tagService->reveal(), Translator::factory([]));
$command = new ListTagsCommand($this->tagService->reveal());
$app = new Application();
$app->add($command);

View file

@ -12,7 +12,6 @@ use Shlinkio\Shlink\Core\Exception\EntityDoesNotExistException;
use Shlinkio\Shlink\Core\Service\Tag\TagServiceInterface;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Zend\I18n\Translator\Translator;
class RenameTagCommandTest extends TestCase
{
@ -33,7 +32,7 @@ class RenameTagCommandTest extends TestCase
{
$this->tagService = $this->prophesize(TagServiceInterface::class);
$command = new RenameTagCommand($this->tagService->reveal(), Translator::factory([]));
$command = new RenameTagCommand($this->tagService->reveal());
$app = new Application();
$app->add($command);

View file

@ -21,7 +21,6 @@ use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\Lock;
use Throwable;
use Zend\I18n\Translator\Translator;
use function array_shift;
use function sprintf;
@ -63,8 +62,7 @@ class ProcessVisitsCommandTest extends TestCase
$command = new ProcessVisitsCommand(
$this->visitService->reveal(),
$this->ipResolver->reveal(),
$this->locker->reveal(),
Translator::factory([])
$this->locker->reveal()
);
$app = new Application();
$app->add($command);

View file

@ -11,7 +11,6 @@ use Shlinkio\Shlink\Common\Exception\RuntimeException;
use Shlinkio\Shlink\Common\IpGeolocation\GeoLite2\DbUpdaterInterface;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Zend\I18n\Translator\Translator;
class UpdateDbCommandTest extends TestCase
{
@ -28,7 +27,7 @@ class UpdateDbCommandTest extends TestCase
{
$this->dbUpdater = $this->prophesize(DbUpdaterInterface::class);
$command = new UpdateDbCommand($this->dbUpdater->reveal(), Translator::factory([]));
$command = new UpdateDbCommand($this->dbUpdater->reveal());
$app = new Application();
$app->add($command);

View file

@ -23,10 +23,9 @@ class ConfigProviderTest extends TestCase
*/
public function confiIsProperlyReturned()
{
$config = $this->configProvider->__invoke();
$config = ($this->configProvider)();
$this->assertArrayHasKey('cli', $config);
$this->assertArrayHasKey('dependencies', $config);
$this->assertArrayHasKey('translator', $config);
}
}

View file

@ -10,7 +10,6 @@ use Shlinkio\Shlink\CLI\Factory\ApplicationFactory;
use Shlinkio\Shlink\Core\Options\AppOptions;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Zend\I18n\Translator\Translator;
use Zend\ServiceManager\ServiceManager;
use function array_merge;
@ -66,7 +65,6 @@ class ApplicationFactoryTest extends TestCase
'cli' => array_merge($config, ['locale' => 'en']),
],
AppOptions::class => new AppOptions(),
Translator::class => Translator::factory([]),
]]);
}

View file

@ -13,6 +13,8 @@ use function explode;
class LocaleMiddleware implements MiddlewareInterface
{
private const ACCEPT_LANGUAGE = 'Accept-Language';
/**
* @var Translator
*/
@ -36,11 +38,11 @@ class LocaleMiddleware implements MiddlewareInterface
*/
public function process(Request $request, DelegateInterface $delegate): Response
{
if (! $request->hasHeader('Accept-Language')) {
if (! $request->hasHeader(self::ACCEPT_LANGUAGE)) {
return $delegate->handle($request);
}
$locale = $request->getHeaderLine('Accept-Language');
$locale = $request->getHeaderLine(self::ACCEPT_LANGUAGE);
$this->translator->setLocale($this->normalizeLocale($locale));
return $delegate->handle($request);
}

View file

@ -19,9 +19,8 @@ class TranslatorExtension implements ExtensionInterface
$this->translator = $translator;
}
public function register(Engine $engine)
public function register(Engine $engine): void
{
$engine->registerFunction('translate', [$this->translator, 'translate']);
$engine->registerFunction('translate_plural', [$this->translator, 'translatePlural']);
}
}

View file

@ -49,19 +49,25 @@ class LocaleMiddlewareTest extends TestCase
/**
* @test
* @dataProvider provideLanguages
*/
public function localeGetsNormalized()
public function localeGetsNormalized(string $lang, string $expected)
{
$delegate = TestUtils::createReqHandlerMock();
$handler = TestUtils::createReqHandlerMock();
$this->assertEquals('ru', $this->translator->getLocale());
$request = ServerRequestFactory::fromGlobals()->withHeader('Accept-Language', 'es_ES');
$this->middleware->process($request, $delegate->reveal());
$this->assertEquals('es', $this->translator->getLocale());
$request = ServerRequestFactory::fromGlobals()->withHeader('Accept-Language', $lang);
$this->middleware->process($request, $handler->reveal());
$this->assertEquals($expected, $this->translator->getLocale());
}
$request = ServerRequestFactory::fromGlobals()->withHeader('Accept-Language', 'en-US');
$this->middleware->process($request, $delegate->reveal());
$this->assertEquals('en', $this->translator->getLocale());
public function provideLanguages(): array
{
return [
['ru', 'ru'],
['es_ES', 'es'],
['en-US', 'en'],
];
}
}

View file

@ -27,10 +27,11 @@ class TranslatorExtensionTest extends TestCase
public function properFunctionsAreReturned()
{
$engine = $this->prophesize(Engine::class);
$registerFunction = $engine->registerFunction('translate', Argument::type('callable'))->will(function () {
});
$engine->registerFunction('translate', Argument::type('callable'))->shouldBeCalledOnce();
$engine->registerFunction('translate_plural', Argument::type('callable'))->shouldBeCalledOnce();
$this->extension->register($engine->reveal());
$funcs = $this->extension->register($engine->reveal());
$registerFunction->shouldHaveBeenCalledOnce();
}
}

View file

@ -1,6 +1,7 @@
<?php
declare(strict_types=1);
use Fig\Http\Message\RequestMethodInterface as RequestMethod;
use RKA\Middleware\IpAddress;
use Shlinkio\Shlink\Core\Action;
use Shlinkio\Shlink\Core\Middleware;
@ -15,7 +16,7 @@ return [
IpAddress::class,
Action\RedirectAction::class,
],
'allowed_methods' => ['GET'],
'allowed_methods' => [RequestMethod::METHOD_GET],
],
[
'name' => 'pixel-tracking',
@ -24,7 +25,7 @@ return [
IpAddress::class,
Action\PixelAction::class,
],
'allowed_methods' => ['GET'],
'allowed_methods' => [RequestMethod::METHOD_GET],
],
[
'name' => 'short-url-qr-code',
@ -33,13 +34,13 @@ return [
Middleware\QrCodeCacheMiddleware::class,
Action\QrCodeAction::class,
],
'allowed_methods' => ['GET'],
'allowed_methods' => [RequestMethod::METHOD_GET],
],
[
'name' => 'short-url-preview',
'path' => '/{shortCode}/preview',
'middleware' => Action\PreviewAction::class,
'allowed_methods' => ['GET'],
'allowed_methods' => [RequestMethod::METHOD_GET],
],
// Old QR code route. Deprecated
@ -50,7 +51,7 @@ return [
Middleware\QrCodeCacheMiddleware::class,
Action\QrCodeAction::class,
],
'allowed_methods' => ['GET'],
'allowed_methods' => [RequestMethod::METHOD_GET],
],
],

View file

@ -55,6 +55,6 @@ class NotFoundHandler implements RequestHandlerInterface
}
$notFoundTemplate = $request->getAttribute(self::NOT_FOUND_TEMPLATE, $this->defaultTemplate);
return new Response\HtmlResponse($this->renderer->render($notFoundTemplate, ['request' => $request]), $status);
return new Response\HtmlResponse($this->renderer->render($notFoundTemplate), $status);
}
}

View file

@ -1,19 +1,19 @@
<?php $this->layout('ShlinkCore::layout/default') ?>
<?php $this->start('title') ?>
<?= $this->translate('URL Not Found') ?>
<?= $this->translate('URL Not Found') ?>
<?php $this->end() ?>
<?php $this->start('stylesheets') ?>
<style>
p {margin-bottom: 20px;}
body {text-align: center;}
</style>
<style>
p {margin-bottom: 20px;}
body {text-align: center;}
</style>
<?php $this->end() ?>
<?php $this->start('main') ?>
<h1>404</h1>
<hr>
<h3><?= $this->translate('Page not found.') ?></h3>
<p><?= $this->translate('The page you requested could not be found.') ?></p>
<h1>404</h1>
<hr>
<h3><?= $this->translate('Page not found.') ?></h3>
<p><?= $this->translate('The page you requested could not be found.') ?></p>
<?php $this->end() ?>

View file

@ -1,25 +1,25 @@
<?php $this->layout('ShlinkCore::layout/default') ?>
<?php $this->start('title') ?>
<?= $this->e($status . ' ' . $reason) ?>
<?= $this->e($status . ' ' . $reason) ?>
<?php $this->end() ?>
<?php $this->start('stylesheets') ?>
<style>
p {margin-bottom: 20px;}
body {text-align: center;}
</style>
<style>
p {margin-bottom: 20px;}
body {text-align: center;}
</style>
<?php $this->end() ?>
<?php $this->start('main') ?>
<h1><?= $this->translate('Oops!') ?></h1>
<hr>
<h1><?= $this->translate('Oops!') ?></h1>
<hr>
<?php if ($status !== 404): ?>
<p><?= sprintf($this->translate('We encountered a %s %s error.'), $status, $reason) ?></p>
<?php else: ?>
<p><?= $this->translate('This short URL doesn\'t seem to be valid.') ?></p>
<p><?= $this->translate('Make sure you included all the characters, with no extra punctuation.') ?></p>
<?php endif; ?>
<?php if ($status !== 404): ?>
<p><?= sprintf($this->translate('We encountered a %s %s error.'), $status, $reason) ?></p>
<?php else: ?>
<p><?= $this->translate('This short URL doesn\'t seem to be valid.') ?></p>
<p><?= $this->translate('Make sure you included all the characters, with no extra punctuation.') ?></p>
<?php endif; ?>
<?php $this->end() ?>

View file

@ -1,42 +1,31 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title><?= $this->section('title', '') ?> | URL shortener</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />
<style>
body {padding-top: 60px;}
.app {display: flex; min-height: 100vh; flex-direction: column;}
.app-content {flex: 1;}
.app-footer p {margin-bottom: 20px;}
</style>
<?= $this->section('stylesheets', '') ?>
<title><?= $this->section('title', '') ?> | URL shortener</title>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<style>
body {padding-top: 60px;}
.app {display: flex; min-height: 100vh; flex-direction: column;}
.app-content {flex: 1;}
.app-footer p {margin-bottom: 20px;}
</style>
<?= $this->section('stylesheets', '') ?>
</head>
<body class="app">
<div class="app-content">
<main class="container">
<?= $this->section('main', '') ?>
</main>
<div class="app-content">
<main class="container">
<?= $this->section('main', '') ?>
</main>
</div>
<footer class="app-footer">
<div class="container">
<hr />
<p>&copy; <?= date('Y') ?> <a href="https://shlink.io">Shlink</a></p>
</div>
<footer class="app-footer">
<div class="container">
<hr />
<?php if ($this->section('footer')): ?>
<?= $this->section('footer') ?>
<?php else: ?>
<p>
&copy; <?= date('Y') ?> <a href="https://shlink.io">Shlink</a>
</p>
<?php endif; ?>
</div>
</footer>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<?= $this->section('javascript', '') ?>
</footer>
</body>
</html>

View file

@ -11,10 +11,8 @@ use function array_keys;
class LanguageConfigCustomizer implements ConfigCustomizerInterface
{
public const DEFAULT_LANG = 'DEFAULT';
public const CLI_LANG = 'CLI';
private const EXPECTED_KEYS = [
self::DEFAULT_LANG,
self::CLI_LANG,
];
private const SUPPORTED_LANGUAGES = ['en', 'es'];
@ -41,9 +39,7 @@ class LanguageConfigCustomizer implements ConfigCustomizerInterface
{
switch ($key) {
case self::DEFAULT_LANG:
return $this->chooseLanguage($io, 'Select default language for the application in general');
case self::CLI_LANG:
return $this->chooseLanguage($io, 'Select default language for CLI executions');
return $this->chooseLanguage($io, 'Select default language for the application error pages');
}
return '';

View file

@ -138,7 +138,6 @@ final class CustomizableAppConfig implements ArraySerializableInterface
$this->setLanguage($this->mapExistingPathsToKeys([
LanguageConfigCustomizer::DEFAULT_LANG => ['translator', 'locale'],
LanguageConfigCustomizer::CLI_LANG => ['cli', 'locale'],
], $pathCollection));
$this->setUrlShortener($this->mapExistingPathsToKeys([
@ -191,9 +190,6 @@ final class CustomizableAppConfig implements ArraySerializableInterface
'translator' => [
'locale' => $this->language[LanguageConfigCustomizer::DEFAULT_LANG] ?? 'en',
],
'cli' => [
'locale' => $this->language[LanguageConfigCustomizer::CLI_LANG] ?? 'en',
],
'url_shortener' => [
'domain' => [
'schema' => $this->urlShortener[UrlShortenerConfigCustomizer::SCHEMA] ?? 'http',

View file

@ -41,9 +41,8 @@ class LanguageConfigCustomizerTest extends TestCase
$this->assertTrue($config->hasLanguage());
$this->assertEquals([
'DEFAULT' => 'en',
'CLI' => 'en',
], $config->getLanguage());
$choice->shouldHaveBeenCalledTimes(2);
$choice->shouldHaveBeenCalledOnce();
}
/**
@ -53,15 +52,11 @@ class LanguageConfigCustomizerTest extends TestCase
{
$choice = $this->io->choice(Argument::cetera())->willReturn('es');
$config = new CustomizableAppConfig();
$config->setLanguage([
'DEFAULT' => 'en',
]);
$this->plugin->process($this->io->reveal(), $config);
$this->assertEquals([
'DEFAULT' => 'en',
'CLI' => 'es',
'DEFAULT' => 'es',
], $config->getLanguage());
$choice->shouldHaveBeenCalledOnce();
}
@ -76,14 +71,12 @@ class LanguageConfigCustomizerTest extends TestCase
$config = new CustomizableAppConfig();
$config->setLanguage([
'DEFAULT' => 'es',
'CLI' => 'es',
]);
$this->plugin->process($this->io->reveal(), $config);
$this->assertEquals([
'DEFAULT' => 'es',
'CLI' => 'es',
], $config->getLanguage());
$choice->shouldNotHaveBeenCalled();
}

View file

@ -38,14 +38,13 @@ return [
],
ConfigAbstractFactory::class => [
Authentication\Plugin\AuthorizationHeaderPlugin::class => [Authentication\JWTService::class, 'translator'],
Authentication\Plugin\ApiKeyHeaderPlugin::class => [Service\ApiKeyService::class, 'translator'],
Authentication\Plugin\AuthorizationHeaderPlugin::class => [Authentication\JWTService::class],
Authentication\Plugin\ApiKeyHeaderPlugin::class => [Service\ApiKeyService::class],
Authentication\RequestToHttpAuthPlugin::class => [Authentication\AuthenticationPluginManager::class],
Middleware\AuthenticationMiddleware::class => [
Authentication\RequestToHttpAuthPlugin::class,
'translator',
'config.auth.routes_whitelist',
'Logger_Shlink',
],

View file

@ -7,7 +7,6 @@ use Psr\Log\LoggerInterface;
use Shlinkio\Shlink\Core\Options\AppOptions;
use Shlinkio\Shlink\Core\Service;
use Shlinkio\Shlink\Rest\Service\ApiKeyService;
use Zend\I18n\Translator\Translator;
use Zend\ServiceManager\AbstractFactory\ConfigAbstractFactory;
use Zend\ServiceManager\Factory\InvokableFactory;
@ -44,52 +43,32 @@ return [
Authentication\JWTService::class => [AppOptions::class],
ApiKeyService::class => ['em'],
Action\AuthenticateAction::class => [
ApiKeyService::class,
Authentication\JWTService::class,
'translator',
'Logger_Shlink',
],
Action\AuthenticateAction::class => [ApiKeyService::class, Authentication\JWTService::class, 'Logger_Shlink'],
Action\ShortUrl\CreateShortUrlAction::class => [
Service\UrlShortener::class,
'translator',
'config.url_shortener.domain',
'Logger_Shlink',
],
Action\ShortUrl\SingleStepCreateShortUrlAction::class => [
Service\UrlShortener::class,
'translator',
ApiKeyService::class,
'config.url_shortener.domain',
'Logger_Shlink',
],
Action\ShortUrl\EditShortUrlAction::class => [Service\ShortUrlService::class, 'translator', 'Logger_Shlink'],
Action\ShortUrl\DeleteShortUrlAction::class => [
Service\ShortUrl\DeleteShortUrlService::class,
'translator',
'Logger_Shlink',
],
Action\ShortUrl\ResolveShortUrlAction::class => [
Service\UrlShortener::class,
'translator',
'config.url_shortener.domain',
],
Action\Visit\GetVisitsAction::class => [Service\VisitsTracker::class, 'translator', 'Logger_Shlink'],
Action\ShortUrl\EditShortUrlAction::class => [Service\ShortUrlService::class, 'Logger_Shlink'],
Action\ShortUrl\DeleteShortUrlAction::class => [Service\ShortUrl\DeleteShortUrlService::class, 'Logger_Shlink'],
Action\ShortUrl\ResolveShortUrlAction::class => [Service\UrlShortener::class, 'config.url_shortener.domain'],
Action\Visit\GetVisitsAction::class => [Service\VisitsTracker::class, 'Logger_Shlink'],
Action\ShortUrl\ListShortUrlsAction::class => [
Service\ShortUrlService::class,
'translator',
'config.url_shortener.domain',
'Logger_Shlink',
],
Action\ShortUrl\EditShortUrlTagsAction::class => [
Service\ShortUrlService::class,
'translator',
'Logger_Shlink',
],
Action\ShortUrl\EditShortUrlTagsAction::class => [Service\ShortUrlService::class, 'Logger_Shlink'],
Action\Tag\ListTagsAction::class => [Service\Tag\TagService::class, LoggerInterface::class],
Action\Tag\DeleteTagsAction::class => [Service\Tag\TagService::class, LoggerInterface::class],
Action\Tag\CreateTagsAction::class => [Service\Tag\TagService::class, LoggerInterface::class],
Action\Tag\UpdateTagAction::class => [Service\Tag\TagService::class, Translator::class, LoggerInterface::class],
Action\Tag\UpdateTagAction::class => [Service\Tag\TagService::class, LoggerInterface::class],
],
];

View file

@ -1,16 +0,0 @@
<?php
declare(strict_types=1);
return [
'translator' => [
'translation_file_patterns' => [
[
'type' => 'gettext',
'base_dir' => __DIR__ . '/../lang',
'pattern' => '%s.mo',
],
],
],
];

Binary file not shown.

View file

@ -1,110 +0,0 @@
msgid ""
msgstr ""
"Project-Id-Version: Shlink 1.0\n"
"POT-Creation-Date: 2018-09-29 10:08+0200\n"
"PO-Revision-Date: 2018-09-29 10:08+0200\n"
"Last-Translator: Alejandro Celaya <alejandro@alejandrocelaya.com>\n"
"Language-Team: \n"
"Language: es_ES\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.0.6\n"
"X-Poedit-Basepath: ..\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: translate;translatePlural\n"
"X-Poedit-SearchPath-0: config\n"
"X-Poedit-SearchPath-1: src\n"
msgid "You have to provide a valid API key under the \"apiKey\" param name."
msgstr ""
"Debes proporcionar una clave de API válida bajo el nombre de parámetro "
"\"apiKey\"."
msgid "Provided API key does not exist or is invalid."
msgstr "La clave de API proporcionada no existe o es inválida."
#, php-format
msgid "Provided URL %s is invalid. Try with a different one."
msgstr "La URL proporcionada \"%s\" es inválida. Prueba con una diferente."
#, php-format
msgid "Provided slug %s is already in use. Try with a different one."
msgstr "El slug proporcionado \"%s\" ya está en uso. Prueba con uno diferente."
msgid "Unexpected error occurred"
msgstr "Ocurrió un error inesperado"
msgid "A URL was not provided"
msgstr "No se ha proporcionado una URL"
#, php-format
msgid "No URL found for short code \"%s\""
msgstr "No se ha encontrado ninguna URL para el código corto \"%s\""
#, php-format
msgid ""
"It is not possible to delete URL with short code \"%s\" because it has "
"reached more than \"%s\" visits."
msgstr ""
"No es posible eliminar la URL con el código corto \"%s\" porque ha alcanzado "
"más de \"%s\" visitas."
msgid "Provided data is invalid."
msgstr "Los datos proporcionados son inválidos."
msgid "A list of tags was not provided"
msgstr "No se ha proporcionado una lista de etiquetas"
#, php-format
msgid "Provided short code \"%s\" has an invalid format"
msgstr "El código corto proporcionado \"%s\" tiene un formato no inválido"
msgid "No API key was provided or it is not valid"
msgstr "No se ha proporcionado una clave de API o esta es inválida"
msgid ""
"You have to provide both 'oldName' and 'newName' params in order to properly "
"rename the tag"
msgstr ""
"Debes proporcionar tanto el parámetro 'oldName' como 'newName' para poder "
"renombrar la etiqueta correctamente"
#, php-format
msgid "It wasn't possible to find a tag with name '%s'"
msgstr "No fue posible encontrar una etiqueta con el nombre '%s'"
#, php-format
msgid "Provided short code %s does not exist"
msgstr "El código corto \"%s\" proporcionado no existe"
#, php-format
msgid "You need to provide the Bearer type in the %s header."
msgstr "Debes proporcionar el typo Bearer en la cabecera %s."
#, php-format
msgid "Provided authorization type %s is not supported. Use Bearer instead."
msgstr ""
"El tipo de autorización proporcionado %s no está soportado. En vez de eso "
"utiliza Bearer."
#, fuzzy, php-format
#| msgid ""
#| "Missing or invalid auth token provided. Perform a new authentication "
#| "request and send provided token on every new request on the \"%s\" header"
msgid ""
"Missing or invalid auth token provided. Perform a new authentication request "
"and send provided token on every new request on the %s header"
msgstr ""
"No se ha proporcionado token de autenticación o este es inválido. Realiza "
"una nueva petición de autenticación y envía el token proporcionado en cada "
"nueva petición en la cabecera \"%s\""
#, php-format
msgid ""
"Expected one of the following authentication headers, but none were "
"provided, [\"%s\"]"
msgstr ""
"Se esperaba una de las siguientes cabeceras de autenticación, pero no se "
"proporcionó ninguna, [\"%s\"]"

View file

@ -11,17 +11,12 @@ use Shlinkio\Shlink\Rest\Service\ApiKeyService;
use Shlinkio\Shlink\Rest\Service\ApiKeyServiceInterface;
use Shlinkio\Shlink\Rest\Util\RestUtils;
use Zend\Diactoros\Response\JsonResponse;
use Zend\I18n\Translator\TranslatorInterface;
class AuthenticateAction extends AbstractRestAction
{
protected const ROUTE_PATH = '/authenticate';
protected const ROUTE_ALLOWED_METHODS = [self::METHOD_POST];
/**
* @var TranslatorInterface
*/
private $translator;
/**
* @var ApiKeyService|ApiKeyServiceInterface
*/
@ -34,11 +29,9 @@ class AuthenticateAction extends AbstractRestAction
public function __construct(
ApiKeyServiceInterface $apiKeyService,
JWTServiceInterface $jwtService,
TranslatorInterface $translator,
LoggerInterface $logger = null
) {
parent::__construct($logger);
$this->translator = $translator;
$this->apiKeyService = $apiKeyService;
$this->jwtService = $jwtService;
}
@ -54,9 +47,7 @@ class AuthenticateAction extends AbstractRestAction
if (! isset($authData['apiKey'])) {
return new JsonResponse([
'error' => RestUtils::INVALID_ARGUMENT_ERROR,
'message' => $this->translator->translate(
'You have to provide a valid API key under the "apiKey" param name.'
),
'message' => 'You have to provide a valid API key under the "apiKey" param name.',
], self::STATUS_BAD_REQUEST);
}
@ -65,7 +56,7 @@ class AuthenticateAction extends AbstractRestAction
if ($apiKey === null || ! $apiKey->isValid()) {
return new JsonResponse([
'error' => RestUtils::INVALID_API_KEY_ERROR,
'message' => $this->translator->translate('Provided API key does not exist or is invalid.'),
'message' => 'Provided API key does not exist or is invalid.',
], self::STATUS_UNAUTHORIZED);
}

View file

@ -16,7 +16,6 @@ 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
@ -29,20 +28,14 @@ abstract class AbstractCreateShortUrlAction extends AbstractRestAction
* @var array
*/
private $domainConfig;
/**
* @var TranslatorInterface
*/
protected $translator;
public function __construct(
UrlShortenerInterface $urlShortener,
TranslatorInterface $translator,
array $domainConfig,
LoggerInterface $logger = null
) {
parent::__construct($logger);
$this->urlShortener = $urlShortener;
$this->translator = $translator;
$this->domainConfig = $domainConfig;
}
@ -82,25 +75,19 @@ abstract class AbstractCreateShortUrlAction extends AbstractRestAction
$this->logger->warning('Provided Invalid URL. {e}', ['e' => $e]);
return new JsonResponse([
'error' => RestUtils::getRestErrorCodeFromException($e),
'message' => sprintf(
$this->translator->translate('Provided URL %s is invalid. Try with a different one.'),
$longUrl
),
'message' => sprintf('Provided URL %s is invalid. Try with a different one.', $longUrl),
], self::STATUS_BAD_REQUEST);
} catch (NonUniqueSlugException $e) {
$this->logger->warning('Provided non-unique slug. {e}', ['e' => $e]);
return new JsonResponse([
'error' => RestUtils::getRestErrorCodeFromException($e),
'message' => sprintf(
$this->translator->translate('Provided slug %s is already in use. Try with a different one.'),
$customSlug
),
'message' => sprintf('Provided slug %s is already in use. Try with a different one.', $customSlug),
], self::STATUS_BAD_REQUEST);
} catch (Throwable $e) {
$this->logger->error('Unexpected error creating short url. {e}', ['e' => $e]);
return new JsonResponse([
'error' => RestUtils::UNKNOWN_ERROR,
'message' => $this->translator->translate('Unexpected error occurred'),
'message' => 'Unexpected error occurred',
], self::STATUS_INTERNAL_SERVER_ERROR);
}
}

View file

@ -8,7 +8,6 @@ use Psr\Http\Message\ServerRequestInterface as Request;
use Shlinkio\Shlink\Core\Exception\InvalidArgumentException;
use Shlinkio\Shlink\Core\Model\CreateShortUrlData;
use Shlinkio\Shlink\Core\Model\ShortUrlMeta;
use Shlinkio\Shlink\Rest\Action\ShortUrl\AbstractCreateShortUrlAction;
use Zend\Diactoros\Uri;
class CreateShortUrlAction extends AbstractCreateShortUrlAction
@ -26,7 +25,7 @@ class CreateShortUrlAction extends AbstractCreateShortUrlAction
{
$postData = (array) $request->getParsedBody();
if (! isset($postData['longUrl'])) {
throw new InvalidArgumentException($this->translator->translate('A URL was not provided'));
throw new InvalidArgumentException('A URL was not provided');
}
return new CreateShortUrlData(

View file

@ -12,7 +12,6 @@ use Shlinkio\Shlink\Rest\Action\AbstractRestAction;
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
@ -24,19 +23,11 @@ class DeleteShortUrlAction extends AbstractRestAction
* @var DeleteShortUrlServiceInterface
*/
private $deleteShortUrlService;
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(
DeleteShortUrlServiceInterface $deleteShortUrlService,
TranslatorInterface $translator,
LoggerInterface $logger = null
) {
public function __construct(DeleteShortUrlServiceInterface $deleteShortUrlService, LoggerInterface $logger = null)
{
parent::__construct($logger);
$this->deleteShortUrlService = $deleteShortUrlService;
$this->translator = $translator;
}
/**
@ -56,13 +47,12 @@ 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('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]);
$messagePlaceholder = $this->translator->translate(
'It is not possible to delete URL with short code "%s" because it has reached more than "%s" visits.'
);
$messagePlaceholder =
'It is not possible to delete URL with short code "%s" because it has reached more than "%s" visits.';
return new JsonResponse([
'error' => RestUtils::getRestErrorCodeFromException($e),

View file

@ -13,7 +13,6 @@ use Shlinkio\Shlink\Rest\Action\AbstractRestAction;
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
@ -25,19 +24,11 @@ class EditShortUrlAction extends AbstractRestAction
* @var ShortUrlServiceInterface
*/
private $shortUrlService;
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(
ShortUrlServiceInterface $shortUrlService,
TranslatorInterface $translator,
LoggerInterface $logger = null
) {
public function __construct(ShortUrlServiceInterface $shortUrlService, LoggerInterface $logger = null)
{
parent::__construct($logger);
$this->shortUrlService = $shortUrlService;
$this->translator = $translator;
}
/**
@ -64,13 +55,13 @@ 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('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]);
return new JsonResponse([
'error' => RestUtils::getRestErrorCodeFromException($e),
'message' => $this->translator->translate('Provided data is invalid.'),
'message' => 'Provided data is invalid.',
], self::STATUS_BAD_REQUEST);
}
}

View file

@ -11,7 +11,6 @@ use Shlinkio\Shlink\Core\Service\ShortUrlServiceInterface;
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 EditShortUrlTagsAction extends AbstractRestAction
@ -23,19 +22,11 @@ class EditShortUrlTagsAction extends AbstractRestAction
* @var ShortUrlServiceInterface
*/
private $shortUrlService;
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(
ShortUrlServiceInterface $shortUrlService,
TranslatorInterface $translator,
LoggerInterface $logger = null
) {
public function __construct(ShortUrlServiceInterface $shortUrlService, LoggerInterface $logger = null)
{
parent::__construct($logger);
$this->shortUrlService = $shortUrlService;
$this->translator = $translator;
}
/**
@ -51,7 +42,7 @@ class EditShortUrlTagsAction extends AbstractRestAction
if (! isset($bodyParams['tags'])) {
return new JsonResponse([
'error' => RestUtils::INVALID_ARGUMENT_ERROR,
'message' => $this->translator->translate('A list of tags was not provided'),
'message' => 'A list of tags was not provided',
], self::STATUS_BAD_REQUEST);
}
$tags = $bodyParams['tags'];
@ -62,7 +53,7 @@ class EditShortUrlTagsAction extends AbstractRestAction
} catch (InvalidShortCodeException $e) {
return new JsonResponse([
'error' => RestUtils::getRestErrorCodeFromException($e),
'message' => sprintf($this->translator->translate('No URL found for short code "%s"'), $shortCode),
'message' => sprintf('No URL found for short code "%s"', $shortCode),
], self::STATUS_NOT_FOUND);
}
}

View file

@ -13,7 +13,6 @@ use Shlinkio\Shlink\Core\Transformer\ShortUrlDataTransformer;
use Shlinkio\Shlink\Rest\Action\AbstractRestAction;
use Shlinkio\Shlink\Rest\Util\RestUtils;
use Zend\Diactoros\Response\JsonResponse;
use Zend\I18n\Translator\TranslatorInterface;
class ListShortUrlsAction extends AbstractRestAction
{
@ -26,10 +25,6 @@ class ListShortUrlsAction extends AbstractRestAction
* @var ShortUrlServiceInterface
*/
private $shortUrlService;
/**
* @var TranslatorInterface
*/
private $translator;
/**
* @var array
*/
@ -37,13 +32,11 @@ class ListShortUrlsAction extends AbstractRestAction
public function __construct(
ShortUrlServiceInterface $shortUrlService,
TranslatorInterface $translator,
array $domainConfig,
LoggerInterface $logger = null
) {
parent::__construct($logger);
$this->shortUrlService = $shortUrlService;
$this->translator = $translator;
$this->domainConfig = $domainConfig;
}
@ -64,7 +57,7 @@ class ListShortUrlsAction extends AbstractRestAction
$this->logger->error('Unexpected error while listing short URLs. {e}', ['e' => $e]);
return new JsonResponse([
'error' => RestUtils::UNKNOWN_ERROR,
'message' => $this->translator->translate('Unexpected error occurred'),
'message' => 'Unexpected error occurred',
], self::STATUS_INTERNAL_SERVER_ERROR);
}
}

View file

@ -14,7 +14,6 @@ use Shlinkio\Shlink\Core\Transformer\ShortUrlDataTransformer;
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
@ -26,10 +25,6 @@ class ResolveShortUrlAction extends AbstractRestAction
* @var UrlShortenerInterface
*/
private $urlShortener;
/**
* @var TranslatorInterface
*/
private $translator;
/**
* @var array
*/
@ -37,13 +32,11 @@ class ResolveShortUrlAction extends AbstractRestAction
public function __construct(
UrlShortenerInterface $urlShortener,
TranslatorInterface $translator,
array $domainConfig,
LoggerInterface $logger = null
) {
parent::__construct($logger);
$this->urlShortener = $urlShortener;
$this->translator = $translator;
$this->domainConfig = $domainConfig;
}
@ -64,22 +57,19 @@ 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(
$this->translator->translate('Provided short code "%s" has an invalid format'),
$shortCode
),
'message' => sprintf('Provided short code "%s" has an invalid format', $shortCode),
], self::STATUS_BAD_REQUEST);
} catch (EntityDoesNotExistException $e) {
$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('No URL found for short code "%s"', $shortCode),
], self::STATUS_NOT_FOUND);
} 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,
'message' => $this->translator->translate('Unexpected error occurred'),
'message' => 'Unexpected error occurred',
], self::STATUS_INTERNAL_SERVER_ERROR);
}
}

View file

@ -10,7 +10,6 @@ use Shlinkio\Shlink\Core\Model\CreateShortUrlData;
use Shlinkio\Shlink\Core\Service\UrlShortenerInterface;
use Shlinkio\Shlink\Rest\Service\ApiKeyServiceInterface;
use Zend\Diactoros\Uri;
use Zend\I18n\Translator\TranslatorInterface;
class SingleStepCreateShortUrlAction extends AbstractCreateShortUrlAction
{
@ -24,12 +23,11 @@ class SingleStepCreateShortUrlAction extends AbstractCreateShortUrlAction
public function __construct(
UrlShortenerInterface $urlShortener,
TranslatorInterface $translator,
ApiKeyServiceInterface $apiKeyService,
array $domainConfig,
LoggerInterface $logger = null
) {
parent::__construct($urlShortener, $translator, $domainConfig, $logger);
parent::__construct($urlShortener, $domainConfig, $logger);
$this->apiKeyService = $apiKeyService;
}
@ -44,13 +42,11 @@ class SingleStepCreateShortUrlAction extends AbstractCreateShortUrlAction
$query = $request->getQueryParams();
if (! $this->apiKeyService->check($query['apiKey'] ?? '')) {
throw new InvalidArgumentException(
$this->translator->translate('No API key was provided or it is not valid')
);
throw new InvalidArgumentException('No API key was provided or it is not valid');
}
if (! isset($query['longUrl'])) {
throw new InvalidArgumentException($this->translator->translate('A URL was not provided'));
throw new InvalidArgumentException('A URL was not provided');
}
return new CreateShortUrlData(new Uri($query['longUrl']));

View file

@ -12,7 +12,6 @@ use Shlinkio\Shlink\Rest\Action\AbstractRestAction;
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 UpdateTagAction extends AbstractRestAction
@ -24,19 +23,11 @@ class UpdateTagAction extends AbstractRestAction
* @var TagServiceInterface
*/
private $tagService;
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(
TagServiceInterface $tagService,
TranslatorInterface $translator,
LoggerInterface $logger = null
) {
public function __construct(TagServiceInterface $tagService, LoggerInterface $logger = null)
{
parent::__construct($logger);
$this->tagService = $tagService;
$this->translator = $translator;
}
/**
@ -54,9 +45,8 @@ class UpdateTagAction extends AbstractRestAction
if (! isset($body['oldName'], $body['newName'])) {
return new JsonResponse([
'error' => RestUtils::INVALID_ARGUMENT_ERROR,
'message' => $this->translator->translate(
'You have to provide both \'oldName\' and \'newName\' params in order to properly rename the tag'
),
'message' =>
'You have to provide both \'oldName\' and \'newName\' params in order to properly rename the tag',
], self::STATUS_BAD_REQUEST);
}
@ -66,10 +56,7 @@ class UpdateTagAction extends AbstractRestAction
} catch (EntityDoesNotExistException $e) {
return new JsonResponse([
'error' => RestUtils::NOT_FOUND_ERROR,
'message' => sprintf(
$this->translator->translate('It wasn\'t possible to find a tag with name \'%s\''),
$body['oldName']
),
'message' => sprintf('It was not possible to find a tag with name %s', $body['oldName']),
], self::STATUS_NOT_FOUND);
}
}

View file

@ -14,7 +14,6 @@ use Shlinkio\Shlink\Core\Service\VisitsTrackerInterface;
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 GetVisitsAction extends AbstractRestAction
@ -26,19 +25,11 @@ class GetVisitsAction extends AbstractRestAction
* @var VisitsTrackerInterface
*/
private $visitsTracker;
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(
VisitsTrackerInterface $visitsTracker,
TranslatorInterface $translator,
LoggerInterface $logger = null
) {
public function __construct(VisitsTrackerInterface $visitsTracker, LoggerInterface $logger = null)
{
parent::__construct($logger);
$this->visitsTracker = $visitsTracker;
$this->translator = $translator;
}
/**
@ -64,16 +55,13 @@ class GetVisitsAction extends AbstractRestAction
$this->logger->warning('Provided nonexistent short code {e}', ['e' => $e]);
return new JsonResponse([
'error' => RestUtils::getRestErrorCodeFromException($e),
'message' => sprintf(
$this->translator->translate('Provided short code %s does not exist'),
$shortCode
),
'message' => sprintf('Provided short code %s does not exist', $shortCode),
], self::STATUS_NOT_FOUND);
} catch (Exception $e) {
$this->logger->error('Unexpected error while parsing short code {e}', ['e' => $e]);
return new JsonResponse([
'error' => RestUtils::UNKNOWN_ERROR,
'message' => $this->translator->translate('Unexpected error occurred'),
'message' => 'Unexpected error occurred',
], self::STATUS_INTERNAL_SERVER_ERROR);
}
}

View file

@ -8,7 +8,6 @@ use Psr\Http\Message\ServerRequestInterface;
use Shlinkio\Shlink\Rest\Exception\VerifyAuthenticationException;
use Shlinkio\Shlink\Rest\Service\ApiKeyServiceInterface;
use Shlinkio\Shlink\Rest\Util\RestUtils;
use Zend\I18n\Translator\TranslatorInterface;
class ApiKeyHeaderPlugin implements AuthenticationPluginInterface
{
@ -18,15 +17,10 @@ class ApiKeyHeaderPlugin implements AuthenticationPluginInterface
* @var ApiKeyServiceInterface
*/
private $apiKeyService;
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(ApiKeyServiceInterface $apiKeyService, TranslatorInterface $translator)
public function __construct(ApiKeyServiceInterface $apiKeyService)
{
$this->apiKeyService = $apiKeyService;
$this->translator = $translator;
}
/**
@ -41,7 +35,7 @@ class ApiKeyHeaderPlugin implements AuthenticationPluginInterface
throw VerifyAuthenticationException::withError(
RestUtils::INVALID_API_KEY_ERROR,
$this->translator->translate('Provided API key does not exist or is invalid.')
'Provided API key does not exist or is invalid.'
);
}

View file

@ -9,7 +9,6 @@ use Shlinkio\Shlink\Rest\Authentication\JWTServiceInterface;
use Shlinkio\Shlink\Rest\Exception\VerifyAuthenticationException;
use Shlinkio\Shlink\Rest\Util\RestUtils;
use Throwable;
use Zend\I18n\Translator\TranslatorInterface;
use function count;
use function explode;
use function sprintf;
@ -23,15 +22,10 @@ class AuthorizationHeaderPlugin implements AuthenticationPluginInterface
* @var JWTServiceInterface
*/
private $jwtService;
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(JWTServiceInterface $jwtService, TranslatorInterface $translator)
public function __construct(JWTServiceInterface $jwtService)
{
$this->jwtService = $jwtService;
$this->translator = $translator;
}
/**
@ -45,10 +39,7 @@ class AuthorizationHeaderPlugin implements AuthenticationPluginInterface
if (count($authTokenParts) === 1) {
throw VerifyAuthenticationException::withError(
RestUtils::INVALID_AUTHORIZATION_ERROR,
sprintf(
$this->translator->translate('You need to provide the Bearer type in the %s header.'),
self::HEADER_NAME
)
sprintf('You need to provide the Bearer type in the %s header.', self::HEADER_NAME)
);
}
@ -57,9 +48,7 @@ class AuthorizationHeaderPlugin implements AuthenticationPluginInterface
if (strtolower($authType) !== 'bearer') {
throw VerifyAuthenticationException::withError(
RestUtils::INVALID_AUTHORIZATION_ERROR,
sprintf($this->translator->translate(
'Provided authorization type %s is not supported. Use Bearer instead.'
), $authType)
sprintf('Provided authorization type %s is not supported. Use Bearer instead.', $authType)
);
}
@ -76,10 +65,11 @@ class AuthorizationHeaderPlugin implements AuthenticationPluginInterface
{
return VerifyAuthenticationException::withError(
RestUtils::INVALID_AUTH_TOKEN_ERROR,
sprintf($this->translator->translate(
sprintf(
'Missing or invalid auth token provided. Perform a new authentication request and send provided '
. 'token on every new request on the %s header'
), self::HEADER_NAME),
. 'token on every new request on the %s header',
self::HEADER_NAME
),
$prev
);
}

View file

@ -19,17 +19,12 @@ use Shlinkio\Shlink\Rest\Exception\VerifyAuthenticationException;
use Shlinkio\Shlink\Rest\Util\RestUtils;
use Zend\Diactoros\Response\JsonResponse;
use Zend\Expressive\Router\RouteResult;
use Zend\I18n\Translator\TranslatorInterface;
use function Functional\contains;
use function implode;
use function sprintf;
class AuthenticationMiddleware implements MiddlewareInterface, StatusCodeInterface, RequestMethodInterface
{
/**
* @var TranslatorInterface
*/
private $translator;
/**
* @var LoggerInterface
*/
@ -45,14 +40,12 @@ class AuthenticationMiddleware implements MiddlewareInterface, StatusCodeInterfa
public function __construct(
RequestToHttpAuthPluginInterface $requestToAuthPlugin,
TranslatorInterface $translator,
array $routesWhitelist,
LoggerInterface $logger = null
) {
$this->translator = $translator;
$this->routesWhitelist = $routesWhitelist;
$this->logger = $logger ?: new NullLogger();
$this->requestToAuthPlugin = $requestToAuthPlugin;
$this->logger = $logger ?: new NullLogger();
}
/**
@ -81,9 +74,10 @@ class AuthenticationMiddleware implements MiddlewareInterface, StatusCodeInterfa
$plugin = $this->requestToAuthPlugin->fromRequest($request);
} catch (ContainerExceptionInterface | NoAuthenticationException $e) {
$this->logger->warning('Invalid or no authentication provided. {e}', ['e' => $e]);
return $this->createErrorResponse(sprintf($this->translator->translate(
'Expected one of the following authentication headers, but none were provided, ["%s"]'
), implode('", "', RequestToHttpAuthPlugin::SUPPORTED_AUTH_HEADERS)));
return $this->createErrorResponse(sprintf(
'Expected one of the following authentication headers, but none were provided, ["%s"]',
implode('", "', RequestToHttpAuthPlugin::SUPPORTED_AUTH_HEADERS)
));
}
try {

View file

@ -8,6 +8,8 @@ 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 Shlinkio\Shlink\Rest\Authentication;
use function implode;
class CrossDomainMiddleware implements MiddlewareInterface, RequestMethodInterface
{
@ -31,7 +33,10 @@ class CrossDomainMiddleware implements MiddlewareInterface, RequestMethodInterfa
// Add Allow-Origin header
$response = $response->withHeader('Access-Control-Allow-Origin', $request->getHeader('Origin'))
->withHeader('Access-Control-Expose-Headers', 'Authorization');
->withHeader('Access-Control-Expose-Headers', implode(', ', [
Authentication\Plugin\ApiKeyHeaderPlugin::HEADER_NAME,
Authentication\Plugin\AuthorizationHeaderPlugin::HEADER_NAME,
]));
if ($request->getMethod() !== self::METHOD_OPTIONS) {
return $response;
}

View file

@ -11,7 +11,6 @@ use Shlinkio\Shlink\Rest\Authentication\JWTService;
use Shlinkio\Shlink\Rest\Entity\ApiKey;
use Shlinkio\Shlink\Rest\Service\ApiKeyService;
use Zend\Diactoros\ServerRequestFactory;
use Zend\I18n\Translator\Translator;
use function strpos;
class AuthenticateActionTest extends TestCase
@ -35,11 +34,7 @@ class AuthenticateActionTest extends TestCase
$this->jwtService = $this->prophesize(JWTService::class);
$this->jwtService->create(Argument::cetera())->willReturn('');
$this->action = new AuthenticateAction(
$this->apiKeyService->reveal(),
$this->jwtService->reveal(),
Translator::factory([])
);
$this->action = new AuthenticateAction($this->apiKeyService->reveal(), $this->jwtService->reveal());
}
/**

View file

@ -15,7 +15,6 @@ use Shlinkio\Shlink\Rest\Action\ShortUrl\CreateShortUrlAction;
use Shlinkio\Shlink\Rest\Util\RestUtils;
use Zend\Diactoros\ServerRequestFactory;
use Zend\Diactoros\Uri;
use Zend\I18n\Translator\Translator;
use function strpos;
class CreateShortUrlActionTest extends TestCase
@ -32,7 +31,7 @@ class CreateShortUrlActionTest extends TestCase
public function setUp()
{
$this->urlShortener = $this->prophesize(UrlShortener::class);
$this->action = new CreateShortUrlAction($this->urlShortener->reveal(), Translator::factory([]), [
$this->action = new CreateShortUrlAction($this->urlShortener->reveal(), [
'schema' => 'http',
'hostname' => 'foo.com',
]);

View file

@ -13,7 +13,6 @@ use Shlinkio\Shlink\Rest\Util\RestUtils;
use Throwable;
use Zend\Diactoros\Response\JsonResponse;
use Zend\Diactoros\ServerRequestFactory;
use Zend\I18n\Translator\Translator;
class DeleteShortUrlActionTest extends TestCase
{
@ -29,7 +28,7 @@ class DeleteShortUrlActionTest extends TestCase
public function setUp()
{
$this->service = $this->prophesize(DeleteShortUrlServiceInterface::class);
$this->action = new DeleteShortUrlAction($this->service->reveal(), Translator::factory([]));
$this->action = new DeleteShortUrlAction($this->service->reveal());
}
/**

View file

@ -13,7 +13,6 @@ use Shlinkio\Shlink\Rest\Action\ShortUrl\EditShortUrlAction;
use Shlinkio\Shlink\Rest\Util\RestUtils;
use Zend\Diactoros\Response\JsonResponse;
use Zend\Diactoros\ServerRequestFactory;
use Zend\I18n\Translator\Translator;
class EditShortUrlActionTest extends TestCase
{
@ -29,7 +28,7 @@ class EditShortUrlActionTest extends TestCase
public function setUp()
{
$this->shortUrlService = $this->prophesize(ShortUrlServiceInterface::class);
$this->action = new EditShortUrlAction($this->shortUrlService->reveal(), Translator::factory([]));
$this->action = new EditShortUrlAction($this->shortUrlService->reveal());
}
/**

View file

@ -10,7 +10,6 @@ use Shlinkio\Shlink\Core\Exception\InvalidShortCodeException;
use Shlinkio\Shlink\Core\Service\ShortUrlService;
use Shlinkio\Shlink\Rest\Action\ShortUrl\EditShortUrlTagsAction;
use Zend\Diactoros\ServerRequestFactory;
use Zend\I18n\Translator\Translator;
class EditShortUrlTagsActionTest extends TestCase
{
@ -26,7 +25,7 @@ class EditShortUrlTagsActionTest extends TestCase
public function setUp()
{
$this->shortUrlService = $this->prophesize(ShortUrlService::class);
$this->action = new EditShortUrlTagsAction($this->shortUrlService->reveal(), Translator::factory([]));
$this->action = new EditShortUrlTagsAction($this->shortUrlService->reveal());
}
/**

View file

@ -9,7 +9,6 @@ use Prophecy\Prophecy\ObjectProphecy;
use Shlinkio\Shlink\Core\Service\ShortUrlService;
use Shlinkio\Shlink\Rest\Action\ShortUrl\ListShortUrlsAction;
use Zend\Diactoros\ServerRequestFactory;
use Zend\I18n\Translator\Translator;
use Zend\Paginator\Adapter\ArrayAdapter;
use Zend\Paginator\Paginator;
@ -27,7 +26,7 @@ class ListShortUrlsActionTest extends TestCase
public function setUp()
{
$this->service = $this->prophesize(ShortUrlService::class);
$this->action = new ListShortUrlsAction($this->service->reveal(), Translator::factory([]), [
$this->action = new ListShortUrlsAction($this->service->reveal(), [
'hostname' => 'doma.in',
'schema' => 'https',
]);

View file

@ -13,7 +13,6 @@ use Shlinkio\Shlink\Core\Service\UrlShortener;
use Shlinkio\Shlink\Rest\Action\ShortUrl\ResolveShortUrlAction;
use Shlinkio\Shlink\Rest\Util\RestUtils;
use Zend\Diactoros\ServerRequestFactory;
use Zend\I18n\Translator\Translator;
use function strpos;
class ResolveShortUrlActionTest extends TestCase
@ -30,7 +29,7 @@ class ResolveShortUrlActionTest extends TestCase
public function setUp()
{
$this->urlShortener = $this->prophesize(UrlShortener::class);
$this->action = new ResolveShortUrlAction($this->urlShortener->reveal(), Translator::factory([]), []);
$this->action = new ResolveShortUrlAction($this->urlShortener->reveal(), []);
}
/**

View file

@ -14,7 +14,6 @@ use Shlinkio\Shlink\Rest\Action\ShortUrl\SingleStepCreateShortUrlAction;
use Shlinkio\Shlink\Rest\Service\ApiKeyServiceInterface;
use Zend\Diactoros\Response\JsonResponse;
use Zend\Diactoros\ServerRequestFactory;
use Zend\I18n\Translator\Translator;
class SingleStepCreateShortUrlActionTest extends TestCase
{
@ -38,7 +37,6 @@ class SingleStepCreateShortUrlActionTest extends TestCase
$this->action = new SingleStepCreateShortUrlAction(
$this->urlShortener->reveal(),
Translator::factory([]),
$this->apiKeyService->reveal(),
[
'schema' => 'http',

View file

@ -11,7 +11,6 @@ use Shlinkio\Shlink\Core\Exception\EntityDoesNotExistException;
use Shlinkio\Shlink\Core\Service\Tag\TagServiceInterface;
use Shlinkio\Shlink\Rest\Action\Tag\UpdateTagAction;
use Zend\Diactoros\ServerRequestFactory;
use Zend\I18n\Translator\Translator;
class UpdateTagActionTest extends TestCase
{
@ -27,7 +26,7 @@ class UpdateTagActionTest extends TestCase
public function setUp()
{
$this->tagService = $this->prophesize(TagServiceInterface::class);
$this->action = new UpdateTagAction($this->tagService->reveal(), Translator::factory([]));
$this->action = new UpdateTagAction($this->tagService->reveal());
}
/**

View file

@ -13,7 +13,6 @@ use Shlinkio\Shlink\Common\Util\DateRange;
use Shlinkio\Shlink\Core\Service\VisitsTracker;
use Shlinkio\Shlink\Rest\Action\Visit\GetVisitsAction;
use Zend\Diactoros\ServerRequestFactory;
use Zend\I18n\Translator\Translator;
class GetVisitsActionTest extends TestCase
{
@ -29,7 +28,7 @@ class GetVisitsActionTest extends TestCase
public function setUp()
{
$this->visitsTracker = $this->prophesize(VisitsTracker::class);
$this->action = new GetVisitsAction($this->visitsTracker->reveal(), Translator::factory([]));
$this->action = new GetVisitsAction($this->visitsTracker->reveal());
}
/**

View file

@ -11,7 +11,6 @@ use Shlinkio\Shlink\Rest\Exception\VerifyAuthenticationException;
use Shlinkio\Shlink\Rest\Service\ApiKeyServiceInterface;
use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequestFactory;
use Zend\I18n\Translator\Translator;
class ApiKeyHeaderPluginTest extends TestCase
{
@ -27,7 +26,7 @@ class ApiKeyHeaderPluginTest extends TestCase
public function setUp()
{
$this->apiKeyService = $this->prophesize(ApiKeyServiceInterface::class);
$this->plugin = new ApiKeyHeaderPlugin($this->apiKeyService->reveal(), Translator::factory([]));
$this->plugin = new ApiKeyHeaderPlugin($this->apiKeyService->reveal());
}
/**

View file

@ -10,7 +10,6 @@ use Shlinkio\Shlink\Rest\Authentication\Plugin\AuthorizationHeaderPlugin;
use Shlinkio\Shlink\Rest\Exception\VerifyAuthenticationException;
use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequestFactory;
use Zend\I18n\Translator\Translator;
use function sprintf;
class AuthorizationHeaderPluginTest extends TestCase
@ -27,7 +26,7 @@ class AuthorizationHeaderPluginTest extends TestCase
public function setUp()
{
$this->jwtService = $this->prophesize(JWTServiceInterface::class);
$this->plugin = new AuthorizationHeaderPlugin($this->jwtService->reveal(), Translator::factory([]));
$this->plugin = new AuthorizationHeaderPlugin($this->jwtService->reveal());
}
/**

View file

@ -28,6 +28,5 @@ class ConfigProviderTest extends TestCase
$this->assertArrayHasKey('error_handler', $config);
$this->assertArrayHasKey('routes', $config);
$this->assertArrayHasKey('dependencies', $config);
$this->assertArrayHasKey('translator', $config);
}
}

View file

@ -25,7 +25,6 @@ use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequestFactory;
use Zend\Expressive\Router\Route;
use Zend\Expressive\Router\RouteResult;
use Zend\I18n\Translator\Translator;
use function implode;
use function sprintf;
use function Zend\Stratigility\middleware;
@ -49,9 +48,7 @@ class AuthenticationMiddlewareTest extends TestCase
public function setUp()
{
$this->requestToPlugin = $this->prophesize(RequestToHttpAuthPluginInterface::class);
$this->middleware = new AuthenticationMiddleware($this->requestToPlugin->reveal(), Translator::factory([]), [
AuthenticateAction::class,
]);
$this->middleware = new AuthenticationMiddleware($this->requestToPlugin->reveal(), [AuthenticateAction::class]);
}
/**