diff --git a/.env.dist b/.env.dist deleted file mode 100644 index daf74cbb..00000000 --- a/.env.dist +++ /dev/null @@ -1,10 +0,0 @@ -# Application -APP_ENV= -SECRET_KEY= -SHORTENED_URL_SCHEMA= -SHORTENED_URL_HOSTNAME= - -# Database -DB_USER= -DB_PASSWORD= -DB_NAME= diff --git a/.gitattributes b/.gitattributes index df9095a4..80102b6f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -9,7 +9,6 @@ /module/PreviewGenerator/test-db export-ignore /module/Rest/test export-ignore /module/Rest/test-api export-ignore -.env.dist export-ignore .gitattributes export-ignore .gitignore export-ignore .phpstorm.meta.php export-ignore diff --git a/.gitignore b/.gitignore index 7b14364c..ab121a93 100644 --- a/.gitignore +++ b/.gitignore @@ -4,7 +4,6 @@ build composer.lock composer.phar vendor/ -.env data/database.sqlite data/shlink-tests.db data/GeoLite2-City.mmdb diff --git a/.travis.yml b/.travis.yml index 6b2a861a..a4b5d1de 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,11 +7,11 @@ branches: php: - '7.2' - '7.3' - - '7.4snapshot' + - '7.4' matrix: allow_failures: - - php: '7.4snapshot' + - php: '7.4' services: - mysql @@ -43,7 +43,8 @@ script: after_success: - rm -f build/clover.xml - - phpdbg -qrr vendor/bin/phpcov merge build --clover build/clover.xml + - wget https://phar.phpunit.de/phpcov-6.0.1.phar + - phpdbg -qrr phpcov-6.0.1.phar merge build --clover build/clover.xml - wget https://scrutinizer-ci.com/ocular.phar - php ocular.phar code-coverage:upload --format=php-clover build/clover.xml diff --git a/CHANGELOG.md b/CHANGELOG.md index 123d0ff4..bb001cb4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,58 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com), and this project adheres to [Semantic Versioning](https://semver.org). +## 1.21.0 - 2019-12-29 + +#### Added + +* [#118](https://github.com/shlinkio/shlink/issues/118) API errors now implement the [problem details](https://tools.ietf.org/html/rfc7807) standard. + + In order to make it backwards compatible, two things have been done: + + * Both the old `error` and `message` properties have been kept on error response, containing the same values as the `type` and `detail` properties respectively. + * The API `v2` has been enabled. If an error occurs when calling the API with this version, the `error` and `message` properties will not be returned. + + > After Shlink v2 is released, both API versions will behave like API v2. + +* [#575](https://github.com/shlinkio/shlink/issues/575) Added support to filter short URL lists by date ranges. + + * The `GET /short-urls` endpoint now accepts the `startDate` and `endDate` query params. + * The `short-urls:list` command now allows `--startDate` and `--endDate` flags to be optionally provided. + +* [#338](https://github.com/shlinkio/shlink/issues/338) Added support to asynchronously notify external services via webhook, only when shlink is served with swoole. + + Configured webhooks will receive a POST request every time a URL receives a visit, including information about the short URL and the visit. + + The payload will look like this: + + ```json + { + "shortUrl": {}, + "visit": {} + } + ``` + + > The `shortUrl` and `visit` props have the same shape as it is defined in the [API spec](https://api-spec.shlink.io). + +#### Changed + +* [#492](https://github.com/shlinkio/shlink/issues/492) Updated to monolog 2, together with other dependencies, like Symfony 5 and infection-php. +* [#527](https://github.com/shlinkio/shlink/issues/527) Increased minimum required mutation score for unit tests to 80%. +* [#557](https://github.com/shlinkio/shlink/issues/557) Added a few php.ini configs for development and production docker images. + +#### Deprecated + +* *Nothing* + +#### Removed + +* *Nothing* + +#### Fixed + +* [#570](https://github.com/shlinkio/shlink/issues/570) Fixed shlink version generated for docker images when building from `develop` branch. + + ## 1.20.3 - 2019-12-23 #### Added diff --git a/Dockerfile b/Dockerfile index eae81a5a..f24dd289 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,7 +1,7 @@ FROM php:7.3.11-alpine3.10 LABEL maintainer="Alejandro Celaya " -ARG SHLINK_VERSION=1.20.0 +ARG SHLINK_VERSION=1.20.2 ENV SHLINK_VERSION ${SHLINK_VERSION} ENV SWOOLE_VERSION 4.4.12 ENV COMPOSER_VERSION 1.9.1 @@ -52,5 +52,6 @@ VOLUME /etc/shlink/config/params # Copy config specific for the image COPY docker/docker-entrypoint.sh docker-entrypoint.sh COPY docker/config/shlink_in_docker.local.php config/autoload/shlink_in_docker.local.php +COPY docker/config/php.ini ${PHP_INI_DIR}/conf.d/ ENTRYPOINT ["/bin/sh", "./docker-entrypoint.sh"] diff --git a/README.md b/README.md index 5eac9951..5f86aeb2 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Shlink +![Shlink](https://raw.githubusercontent.com/shlinkio/shlink.io/master/public/images/shlink-hero.png) [![Build Status](https://img.shields.io/travis/shlinkio/shlink.svg?style=flat-square)](https://travis-ci.org/shlinkio/shlink) [![Code Coverage](https://img.shields.io/scrutinizer/coverage/g/shlinkio/shlink.svg?style=flat-square)](https://scrutinizer-ci.com/g/shlinkio/shlink/?branch=master) @@ -12,26 +12,36 @@ A PHP-based self-hosted URL shortener that can be used to serve shortened URLs u ## Table of Contents - [Installation](#installation) + - [Download](#download) + - [Configure](#configure) + - [Serve](#serve) + - [Bonus](#bonus) - [Update to new version](#update-to-new-version) - [Using a docker image](#using-a-docker-image) - [Using shlink](#using-shlink) - - [Shlink CLI Help](#shlink-cli-help) + - [Shlink CLI Help](#shlink-cli-help) ## Installation -First make sure the host where you are going to run shlink fulfills these requirements: +> These are the steps needed to install Shlink if you plan to manually host it. +> +> Alternatively, you can use the official docker image. If that's your intention, jump directly to [Using a docker image](#using-a-docker-image) + +First, make sure the host where you are going to run shlink fulfills these requirements: * PHP 7.2 or greater with JSON, APCu, intl, curl, PDO and gd extensions enabled. * MySQL, MariaDB, PostgreSQL or SQLite. * The web server of your choice with PHP integration (Apache or Nginx recommended). -Then, you will need a built version of the project. There are a few ways to get it. +### Download + +In order to run Shlink, you will need a built version of the project. There are two ways to get it. * **Using a dist file** The easiest way to install shlink is by using one of the pre-bundled distributable packages. - Just go to the [latest version](https://github.com/shlinkio/shlink/releases/latest) and download the `shlink_X.X.X_dist.zip` file you will find there. + Go to the [latest version](https://github.com/shlinkio/shlink/releases/latest) and download the `shlink_x.x.x_dist.zip` file you will find there. Finally, decompress the file in the location of your choice. @@ -43,158 +53,159 @@ Then, you will need a built version of the project. There are a few ways to get * Download the [Composer](https://getcomposer.org/download/) PHP package manager inside the project folder. * Run `./build.sh 1.0.0`, replacing the version with the version number you are going to build (the version number is only used for the generated dist file). - After that, you will have a `shlink_x.x.x_dist.zip` dist file inside the `build` directory. + After that, you will have a `shlink_x.x.x_dist.zip` dist file inside the `build` directory, that you need to decompress in the location fo your choice. - This is the process used when releasing new shlink versions. After tagging the new version with git, the Github release is automatically created by [travis](https://travis-ci.org/shlinkio/shlink), attaching generated dist file to it. + > This is the process used when releasing new shlink versions. After tagging the new version with git, the Github release is automatically created by [travis](https://travis-ci.org/shlinkio/shlink), attaching the generated dist file to it. -Despite how you built the project, you are going to need to install it now, by following these steps: +### Configure + +Despite how you built the project, you now need to configure it, by following these steps: * If you are going to use MySQL, MariaDB or PostgreSQL, create an empty database with the name of your choice. * Recursively grant write permissions to the `data` directory. Shlink uses it to cache some information. * Setup the application by running the `bin/install` script. It is a command line tool that will guide you through the installation process. **Take into account that this tool has to be run directly on the server where you plan to host Shlink. Do not run it before uploading/moving it there.** -* Expose shlink to the web, either by using a traditional web server + fast CGI approach, or by using a [swoole](https://www.swoole.co.uk/) non-blocking server. - - * **Using a web server:** - - For example, assuming your domain is doma.in and shlink is in the `/path/to/shlink` folder, these would be the basic configurations for Nginx and Apache. - - *Nginx:* - - ```nginx - server { - server_name doma.in; - listen 80; - root /path/to/shlink/public; - index index.php; - charset utf-8; - - location / { - try_files $uri $uri/ /index.php$is_args$args; - } - - location ~ \.php$ { - fastcgi_split_path_info ^(.+\.php)(/.+)$; - fastcgi_pass unix:/var/run/php/php7.2-fpm.sock; - fastcgi_index index.php; - include fastcgi.conf; - } - - location ~ /\.ht { - deny all; - } - } - ``` - - *Apache:* - - ```apache - - ServerName doma.in - DocumentRoot "/path/to/shlink/public" - - - Options FollowSymLinks Includes ExecCGI - AllowOverride all - Order allow,deny - Allow from all - - - ``` - - * **Using swoole:** - - First you need to install the swoole PHP extension with [pecl](https://pecl.php.net/package/swoole), `pecl install swoole`. - - Once installed, it's actually pretty easy to get shlink up and running with swoole. Just run `./vendor/bin/zend-expressive-swoole start -d` and you will get shlink running on port 8080. - - However, by doing it this way, you are loosing all the access logs, and the service won't be automatically run if the server has to be restarted. - - For that reason, you should create a daemon script, in `/etc/init.d/shlink_swoole`, like this one, replacing `/path/to/shlink` by the path to your shlink installation: - - ```bash - #!/bin/bash - ### BEGIN INIT INFO - # Provides: shlink_swoole - # Required-Start: $local_fs $network $named $time $syslog - # Required-Stop: $local_fs $network $named $time $syslog - # Default-Start: 2 3 4 5 - # Default-Stop: 0 1 6 - # Description: Shlink non-blocking server with swoole - ### END INIT INFO - - SCRIPT=/path/to/shlink/vendor/bin/zend-expressive-swoole\ start - RUNAS=root - - PIDFILE=/var/run/shlink_swoole.pid - LOGDIR=/var/log/shlink - LOGFILE=${LOGDIR}/shlink_swoole.log - - start() { - if [[ -f "$PIDFILE" ]] && kill -0 $(cat "$PIDFILE"); then - echo 'Shlink with swoole already running' >&2 - return 1 - fi - echo 'Starting shlink with swoole' >&2 - mkdir -p "$LOGDIR" - touch "$LOGFILE" - local CMD="$SCRIPT &> \"$LOGFILE\" & echo \$!" - su -c "$CMD" $RUNAS > "$PIDFILE" - echo 'Shlink started' >&2 - } - - stop() { - if [[ ! -f "$PIDFILE" ]] || ! kill -0 $(cat "$PIDFILE"); then - echo 'Shlink with swoole not running' >&2 - return 1 - fi - echo 'Stopping shlink with swoole' >&2 - kill -15 $(cat "$PIDFILE") && rm -f "$PIDFILE" - echo 'Shlink stopped' >&2 - } - - case "$1" in - start) - start - ;; - stop) - stop - ;; - restart) - stop - start - ;; - *) - echo "Usage: $0 {start|stop|restart}" - esac - ``` - - Then run these commands to enable the service and start it: - - * `sudo chmod +x /etc/init.d/shlink_swoole` - * `sudo update-rc.d shlink_swoole defaults` - * `sudo update-rc.d shlink_swoole enable` - * `/etc/init.d/shlink_swoole start` - - Now again, you can access shlink on port 8080, but this time the service will be automatically run at system start-up, and all access logs will be written in `/var/log/shlink/shlink_swoole.log` (you will probably want to [rotate those logs](https://www.digitalocean.com/community/tutorials/how-to-manage-logfiles-with-logrotate-on-ubuntu-16-04). You can find an example logrotate config file [here](data/infra/examples/shlink-daemon-logrotate.conf)). - * Generate your first API key by running `bin/cli api-key:generate`. You will need the key in order to interact with shlink's API. -* Finally access to [https://app.shlink.io](https://app.shlink.io) and configure your server to start creating short URLs. -**Bonus** +### Serve -There are a couple of time-consuming tasks that shlink expects you to do manually, or at least it is recommended, since it will improve runtime performance. +Once Shlink is configured, you need to expose it to the web, either by using a traditional web server + fast CGI approach, or by using a [swoole](https://www.swoole.co.uk/) non-blocking server. -Those tasks can be performed using shlink's CLI, so it should be easy to schedule them to be run in the background (for example, using cron jobs): +* **Using a web server:** -* **For shlink older than 1.18.0 or not using swoole as the web server**: Resolve IP address locations: `/path/to/shlink/bin/cli visit:locate` + For example, assuming your domain is doma.in and shlink is in the `/path/to/shlink` folder, these would be the basic configurations for Nginx and Apache. + + *Nginx:* + + ```nginx + server { + server_name doma.in; + listen 80; + root /path/to/shlink/public; + index index.php; + charset utf-8; + + location / { + try_files $uri $uri/ /index.php$is_args$args; + } + + location ~ \.php$ { + fastcgi_split_path_info ^(.+\.php)(/.+)$; + fastcgi_pass unix:/var/run/php/php7.2-fpm.sock; + fastcgi_index index.php; + include fastcgi.conf; + } + + location ~ /\.ht { + deny all; + } + } + ``` + + *Apache:* + + ```apache + + ServerName doma.in + DocumentRoot "/path/to/shlink/public" + + + Options FollowSymLinks Includes ExecCGI + AllowOverride all + Order allow,deny + Allow from all + + + ``` + +* **Using swoole:** + + First you need to install the swoole PHP extension with [pecl](https://pecl.php.net/package/swoole), `pecl install swoole`. + + Once installed, it's actually pretty easy to get shlink up and running with swoole. Run `./vendor/bin/zend-expressive-swoole start -d` and you will get shlink running on port 8080. + + However, by doing it this way, you are loosing all the access logs, and the service won't be automatically run if the server has to be restarted. + + For that reason, you should create a daemon script, in `/etc/init.d/shlink_swoole`, like this one, replacing `/path/to/shlink` by the path to your shlink installation: + + ```bash + #!/bin/bash + ### BEGIN INIT INFO + # Provides: shlink_swoole + # Required-Start: $local_fs $network $named $time $syslog + # Required-Stop: $local_fs $network $named $time $syslog + # Default-Start: 2 3 4 5 + # Default-Stop: 0 1 6 + # Description: Shlink non-blocking server with swoole + ### END INIT INFO + + SCRIPT=/path/to/shlink/vendor/bin/zend-expressive-swoole\ start + RUNAS=root + + PIDFILE=/var/run/shlink_swoole.pid + LOGDIR=/var/log/shlink + LOGFILE=${LOGDIR}/shlink_swoole.log + + start() { + if [[ -f "$PIDFILE" ]] && kill -0 $(cat "$PIDFILE"); then + echo 'Shlink with swoole already running' >&2 + return 1 + fi + echo 'Starting shlink with swoole' >&2 + mkdir -p "$LOGDIR" + touch "$LOGFILE" + local CMD="$SCRIPT &> \"$LOGFILE\" & echo \$!" + su -c "$CMD" $RUNAS > "$PIDFILE" + echo 'Shlink started' >&2 + } + + stop() { + if [[ ! -f "$PIDFILE" ]] || ! kill -0 $(cat "$PIDFILE"); then + echo 'Shlink with swoole not running' >&2 + return 1 + fi + echo 'Stopping shlink with swoole' >&2 + kill -15 $(cat "$PIDFILE") && rm -f "$PIDFILE" + echo 'Shlink stopped' >&2 + } + + case "$1" in + start) + start + ;; + stop) + stop + ;; + restart) + stop + start + ;; + *) + echo "Usage: $0 {start|stop|restart}" + esac + ``` + + Then run these commands to enable the service and start it: + + * `sudo chmod +x /etc/init.d/shlink_swoole` + * `sudo update-rc.d shlink_swoole defaults` + * `sudo update-rc.d shlink_swoole enable` + * `/etc/init.d/shlink_swoole start` + + Now again, you can access shlink on port 8080, but this time the service will be automatically run at system start-up, and all access logs will be written in `/var/log/shlink/shlink_swoole.log` (you will probably want to [rotate those logs](https://www.digitalocean.com/community/tutorials/how-to-manage-logfiles-with-logrotate-on-ubuntu-16-04). You can find an example logrotate config file [here](data/infra/examples/shlink-daemon-logrotate.conf)). + +Finally access to [https://app.shlink.io](https://app.shlink.io) and configure your server to start creating short URLs. + +### Bonus + +Depending on the shlink version you installed and how you serve it, there are a couple of time-consuming tasks that shlink expects you to do manually, or at least it is recommended, since it will improve runtime performance. + +Those tasks can be performed using shlink's CLI tool, so it should be easy to schedule them to be run in the background (for example, using cron jobs): + +* **For shlink older than 1.18.0 or not using swoole to serve it**: Resolve IP address locations: `/path/to/shlink/bin/cli visit:locate` If you don't run this command regularly, the stats will say all visits come from *unknown* locations. -* Generate website previews: `/path/to/shlink/bin/cli short-url:process-previews` - - Running this will improve the performance of the `doma.in/abc123/preview` URLs, which return a preview of the site. - - > **Important!** Generating previews is considered deprecated and the feature will be removed in Shlink v2. + > If you serve Shlink with swoole and use v1.18.0 at least, visit location is automatically scheduled by Shlink just after the visit occurs, using swoole's task system. * **For shlink older than v1.17.0**: Update IP geolocation database: `/path/to/shlink/bin/cli visit:update-db` @@ -202,24 +213,28 @@ Those tasks can be performed using shlink's CLI, so it should be easy to schedul The file is updated the first Tuesday of every month, so it should be enough running this command the first Wednesday. -*Any of these commands accept the `-q` flag, which makes it not display any output. This is recommended when configuring the commands as cron jobs.* + > You don't need this if you use Shlink v1.17.0 or newer, since now it downloads/updates the geolocation database automatically just before trying to use it. -> In future versions, it is planed that, when using **swoole** to serve shlink, some of these tasks are automatically run without blocking the request and also, without having to configure cron jobs. Probably resolving IP locations and generating previews. +* Generate website previews: `/path/to/shlink/bin/cli short-url:process-previews` + + Running this will improve the performance of the `doma.in/abc123/preview` URLs, which return a preview of the site. + + > **Important!** Generating previews is considered deprecated and the feature will be removed in Shlink v2. + +*Any of these commands accept the `-q` flag, which makes it not display any output. This is recommended when configuring the commands as cron jobs.* ## Update to new version -When a new Shlink version is available, you don't need to repeat the entire process yourself. Instead, follow these steps: +When a new Shlink version is available, you don't need to repeat the entire process. Instead, follow these steps: 1. Rename your existing Shlink directory to something else (ie. `shlink` ---> `shlink-old`). -2. Download and extract the new version of Shlink, and set the directories name to that of the old version. (ie. `shlink`). -3. Run the `bin/update` script in the new version's directory to migrate your configuration over. +2. Download and extract the new version of Shlink, and set the directory name to that of the old version (ie. `shlink`). +3. Run the `bin/update` script in the new version's directory to migrate your configuration over. You will be asked to provide the path to the old instance (ie. `shlink-old`). 4. If you are using shlink with swoole, restart the service by running `/etc/init.d/shlink_swoole restart`. -The `bin/update` script will ask you for the location from previous shlink version, and use it in order to import the configuration. It will then update the database and generate some assets shlink needs to work. +The `bin/update` will use the location from previous shlink version to import the configuration. It will then update the database and generate some assets shlink needs to work. -Right now, it does not import cached info (like website previews), but it will. For now you will need to regenerate them again. - -**Important!** It is recommended that you don't skip any version when using this process. The update gets better on every version, but older versions might make assumptions. +**Important!** It is recommended that you don't skip any version when using this process. The update tool gets better on every version, but older versions might make assumptions. ## Using a docker image @@ -237,7 +252,7 @@ Once shlink is installed, there are two main ways to interact with it: It is probably a good idea to symlink the CLI entry point (`bin/cli`) to somewhere in your path, so that you can run shlink from any directory. -* **The REST API**. The complete docs on how to use the API can be found [here](https://shlink.io/api-docs), and a sandbox which also documents every endpoint can be found [here](https://shlink.io/swagger-ui/index.html). +* **The REST API**. The complete docs on how to use the API can be found [here](https://shlink.io/api-docs), and a sandbox which also documents every endpoint can be found in the [API Spec](https://api-spec.shlink.io/) portal. However, you probably don't want to consume the raw API yourself. That's why a nice [web client](https://github.com/shlinkio/shlink-web-client) is provided that can be directly used from [https://app.shlink.io](https://app.shlink.io), or you can host it yourself too. diff --git a/bin/cli b/bin/cli index 7f512eb0..c185efd3 100755 --- a/bin/cli +++ b/bin/cli @@ -1,10 +1,7 @@ #!/usr/bin/env php get(CliApp::class)->run(); +$run = require __DIR__ . '/../config/run.php'; +$run(true); diff --git a/bin/test/run-api-tests.sh b/bin/test/run-api-tests.sh index 75a51387..cbc10a1a 100755 --- a/bin/test/run-api-tests.sh +++ b/bin/test/run-api-tests.sh @@ -9,7 +9,7 @@ echo 'Starting server...' vendor/bin/zend-expressive-swoole start -d sleep 2 -vendor/bin/phpunit --order-by=random -c phpunit-api.xml --testdox --colors=always +vendor/bin/phpunit --order-by=random -c phpunit-api.xml --testdox --colors=always $* testsExitCode=$? vendor/bin/zend-expressive-swoole stop diff --git a/composer.json b/composer.json index 34787bd9..7782f61d 100644 --- a/composer.json +++ b/composer.json @@ -15,34 +15,33 @@ "php": "^7.2", "ext-json": "*", "ext-pdo": "*", - "acelaya/ze-content-based-error-handler": "^3.0", "akrabat/ip-address-middleware": "^1.0", "cakephp/chronos": "^1.2", "cocur/slugify": "^3.0", - "doctrine/cache": "^1.6", - "doctrine/dbal": "^2.9", - "doctrine/migrations": "^2.0", - "doctrine/orm": "^2.5", + "doctrine/cache": "^1.9", + "doctrine/dbal": "^2.10", + "doctrine/migrations": "^2.2", + "doctrine/orm": "^2.7", "endroid/qr-code": "^3.6", "firebase/php-jwt": "^4.0", "geoip2/geoip2": "^2.9", - "guzzlehttp/guzzle": "^6.3", + "guzzlehttp/guzzle": "^6.5.1", "lstrojny/functional-php": "^1.9", "mikehaertl/phpwkhtmltopdf": "^2.2", - "monolog/monolog": "^1.24", + "monolog/monolog": "^2.0", + "nikolaposa/monolog-factory": "^3.0", "ocramius/proxy-manager": "~2.2.2", "phly/phly-event-dispatcher": "^1.0", "predis/predis": "^1.1", "pugx/shortid-php": "^0.5", - "shlinkio/shlink-common": "^2.2.1", - "shlinkio/shlink-event-dispatcher": "^1.0", - "shlinkio/shlink-installer": "^3.1", - "shlinkio/shlink-ip-geolocation": "^1.1", - "symfony/console": "^4.3", - "symfony/filesystem": "^4.3", - "symfony/lock": "^4.3", - "symfony/process": "^4.3", - "theorchard/monolog-cascade": "^0.5", + "shlinkio/shlink-common": "^2.4", + "shlinkio/shlink-event-dispatcher": "^1.1", + "shlinkio/shlink-installer": "^3.3", + "shlinkio/shlink-ip-geolocation": "^1.2", + "symfony/console": "^5.0", + "symfony/filesystem": "^5.0", + "symfony/lock": "^5.0", + "symfony/process": "^5.0", "zendframework/zend-config": "^3.3", "zendframework/zend-config-aggregator": "^1.1", "zendframework/zend-diactoros": "^2.1.3", @@ -53,24 +52,20 @@ "zendframework/zend-expressive-swoole": "^2.4", "zendframework/zend-inputfilter": "^2.10", "zendframework/zend-paginator": "^2.8", + "zendframework/zend-problem-details": "^1.0", "zendframework/zend-servicemanager": "^3.4", "zendframework/zend-stdlib": "^3.2" }, "require-dev": { "devster/ubench": "^2.0", "eaglewu/swoole-ide-helper": "dev-master", - "filp/whoops": "^2.4", - "infection/infection": "^0.14.2", - "phpstan/phpstan": "^0.11.16", - "phpunit/phpcov": "^6.0", + "infection/infection": "^0.15.0", + "phpstan/phpstan-shim": "^0.11.16", "phpunit/phpunit": "^8.3", "roave/security-advisories": "dev-master", "shlinkio/php-coding-standard": "~2.0.0", - "shlinkio/shlink-test-utils": "^1.0", - "symfony/dotenv": "^4.3", - "symfony/var-dumper": "^4.3", - "zendframework/zend-component-installer": "^2.1", - "zendframework/zend-expressive-tooling": "^1.2" + "shlinkio/shlink-test-utils": "^1.2", + "symfony/var-dumper": "^5.0" }, "autoload": { "psr-4": { @@ -116,7 +111,7 @@ "@test:api" ], "test:unit": "phpdbg -qrr vendor/bin/phpunit --order-by=random --colors=always --coverage-php build/coverage-unit.cov --testdox", - "test:unit:ci": "phpdbg -qrr vendor/bin/phpunit --order-by=random --colors=always --coverage-php build/coverage-unit.cov --coverage-clover=build/clover.xml --coverage-xml=build/coverage-xml --log-junit=build/phpunit.junit.xml --testdox", + "test:unit:ci": "@test:unit --coverage-clover=build/clover.xml --coverage-xml=build/coverage-xml --log-junit=build/junit.xml", "test:db": [ "@test:db:sqlite", "@test:db:mysql", @@ -128,19 +123,15 @@ "@test:db:mysql", "@test:db:postgres" ], - "test:db:sqlite": "APP_ENV=test phpdbg -qrr vendor/bin/phpunit --order-by=random --colors=always -c phpunit-db.xml --coverage-php build/coverage-db.cov --testdox", + "test:db:sqlite": "APP_ENV=test phpdbg -qrr vendor/bin/phpunit --order-by=random --colors=always --coverage-php build/coverage-db.cov --testdox -c phpunit-db.xml", "test:db:mysql": "DB_DRIVER=mysql composer test:db:sqlite", "test:db:maria": "DB_DRIVER=maria composer test:db:sqlite", "test:db:postgres": "DB_DRIVER=postgres composer test:db:sqlite", "test:api": "bin/test/run-api-tests.sh", - "test:pretty": [ - "@test", - "phpdbg -qrr vendor/bin/phpcov merge build --html build/html" - ], "test:unit:pretty": "phpdbg -qrr vendor/bin/phpunit --order-by=random --colors=always --coverage-html build/coverage", - "infect": "infection --threads=4 --min-msi=75 --log-verbosity=default --only-covered", - "infect:ci": "infection --threads=4 --min-msi=75 --log-verbosity=default --only-covered --coverage=build", - "infect:show": "infection --threads=4 --min-msi=75 --log-verbosity=default --only-covered --show-mutations", + "infect": "infection --threads=4 --min-msi=80 --log-verbosity=default --only-covered", + "infect:ci": "@infect --coverage=build", + "infect:show": "@infect --show-mutations", "infect:test": [ "@test:unit:ci", "@infect:ci" @@ -163,7 +154,6 @@ "test:db:maria": "Runs database test suites on a MariaDB database", "test:db:postgres": "Runs database test suites on a PostgreSQL database", "test:api": "Runs API test suites", - "test:pretty": "Runs all test suites and generates an HTML code coverage report", "test:unit:pretty": "Runs unit test suites and generates an HTML code coverage report", "infect": "Checks unit tests quality applying mutation testing", "infect:ci": "Checks unit tests quality applying mutation testing with existing reports and logs", diff --git a/config/autoload/entity-manager.global.php b/config/autoload/entity-manager.global.php index bd847f5a..561579f1 100644 --- a/config/autoload/entity-manager.global.php +++ b/config/autoload/entity-manager.global.php @@ -11,9 +11,9 @@ return [ 'proxies_dir' => 'data/proxies', ], 'connection' => [ - 'user' => env('DB_USER'), - 'password' => env('DB_PASSWORD'), - 'dbname' => env('DB_NAME', 'shlink'), + 'user' => '', + 'password' => '', + 'dbname' => 'shlink', 'charset' => 'utf8', ], ], diff --git a/config/autoload/entity-manager.local.php.dist b/config/autoload/entity-manager.local.php.dist index cb53a6ae..3c38fb82 100644 --- a/config/autoload/entity-manager.local.php.dist +++ b/config/autoload/entity-manager.local.php.dist @@ -1,8 +1,13 @@ [ 'connection' => [ + 'user' => 'root', + 'password' => 'root', 'driver' => 'pdo_mysql', 'host' => 'shlink_db', 'driverOptions' => [ diff --git a/config/autoload/error-handler.global.php b/config/autoload/error-handler.global.php new file mode 100644 index 00000000..964b90de --- /dev/null +++ b/config/autoload/error-handler.global.php @@ -0,0 +1,34 @@ + [ + 'default_type_fallbacks' => [ + 404 => 'NOT_FOUND', + 500 => 'INTERNAL_SERVER_ERROR', + ], + 'json_flags' => JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION, + ], + + 'error_handler' => [ + 'listeners' => [Logger\ErrorLogger::class], + ], + + 'dependencies' => [ + 'delegators' => [ + ErrorHandler::class => [ + Logger\ErrorHandlerListenerAttachingDelegator::class, + ], + ProblemDetailsMiddleware::class => [ + Logger\ErrorHandlerListenerAttachingDelegator::class, + ], + ], + ], + +]; diff --git a/config/autoload/errorhandler.local.php.dist b/config/autoload/errorhandler.local.php.dist deleted file mode 100644 index 6dea98cb..00000000 --- a/config/autoload/errorhandler.local.php.dist +++ /dev/null @@ -1,29 +0,0 @@ - [ - 'invokables' => [ - 'Zend\Expressive\Whoops' => Whoops\Run::class, - 'Zend\Expressive\WhoopsPageHandler' => Whoops\Handler\PrettyPageHandler::class, - ], - ], - - 'whoops' => [ - 'json_exceptions' => [ - 'display' => true, - 'show_trace' => true, - 'ajax_only' => true, - ], - ], - - 'error_handler' => [ - 'plugins' => [ - 'factories' => [ - 'text/html' => WhoopsErrorResponseGeneratorFactory::class, - ], - ], - ], -]; diff --git a/config/autoload/installer.global.php b/config/autoload/installer.global.php index 91ebdab7..402e6bb3 100644 --- a/config/autoload/installer.global.php +++ b/config/autoload/installer.global.php @@ -11,6 +11,8 @@ return [ Plugin\UrlShortenerConfigCustomizer::SCHEMA, Plugin\UrlShortenerConfigCustomizer::HOSTNAME, Plugin\UrlShortenerConfigCustomizer::VALIDATE_URL, + Plugin\UrlShortenerConfigCustomizer::NOTIFY_VISITS_WEBHOOKS, + Plugin\UrlShortenerConfigCustomizer::VISITS_WEBHOOKS, ], Plugin\ApplicationConfigCustomizer::class => [ diff --git a/config/autoload/locks.global.php b/config/autoload/locks.global.php index 8462e15b..0294bf91 100644 --- a/config/autoload/locks.global.php +++ b/config/autoload/locks.global.php @@ -20,7 +20,7 @@ return [ 'factories' => [ Lock\Store\FlockStore::class => ConfigAbstractFactory::class, Lock\Store\RedisStore::class => ConfigAbstractFactory::class, - Lock\Factory::class => ConfigAbstractFactory::class, + Lock\LockFactory::class => ConfigAbstractFactory::class, $localLockFactory => ConfigAbstractFactory::class, ], 'aliases' => [ @@ -34,7 +34,7 @@ return [ Lock\Store\RedisStore::class => [ RetryLockStoreDelegatorFactory::class, ], - Lock\Factory::class => [ + Lock\LockFactory::class => [ LoggerAwareDelegatorFactory::class, ], ], @@ -43,7 +43,7 @@ return [ ConfigAbstractFactory::class => [ Lock\Store\FlockStore::class => ['config.locks.locks_dir'], Lock\Store\RedisStore::class => [RedisFactory::SERVICE_NAME], - Lock\Factory::class => ['lock_store'], + Lock\LockFactory::class => ['lock_store'], $localLockFactory => ['local_lock_store'], ], diff --git a/config/autoload/logger.global.php b/config/autoload/logger.global.php index 6b0df063..40aa8a2d 100644 --- a/config/autoload/logger.global.php +++ b/config/autoload/logger.global.php @@ -4,64 +4,69 @@ declare(strict_types=1); namespace Shlinkio\Shlink; -use Monolog\Handler\RotatingFileHandler; -use Monolog\Handler\StreamHandler; +use Monolog\Formatter; +use Monolog\Handler; use Monolog\Logger; use Monolog\Processor; +use MonologFactory\DiContainerLoggerFactory; use Psr\Log\LoggerInterface; use const PHP_EOL; +$processors = [ + 'exception_with_new_line' => [ + 'name' => Common\Logger\Processor\ExceptionWithNewLineProcessor::class, + ], + 'psr3' => [ + 'name' => Processor\PsrLogMessageProcessor::class, + ], +]; +$formatter = [ + 'name' => Formatter\LineFormatter::class, + 'params' => [ + 'format' => '[%datetime%] %channel%.%level_name% - %message%' . PHP_EOL, + 'allow_inline_line_breaks' => true, + ], +]; + return [ 'logger' => [ - 'formatters' => [ - 'dashed' => [ - 'format' => '[%datetime%] %channel%.%level_name% - %message%' . PHP_EOL, - 'include_stacktraces' => true, + 'Shlink' => [ + 'name' => 'Shlink', + 'handlers' => [ + 'shlink_handler' => [ + 'name' => Handler\RotatingFileHandler::class, + 'params' => [ + 'level' => Logger::INFO, + 'filename' => 'data/log/shlink_log.log', + 'max_files' => 30, + ], + 'formatter' => $formatter, + ], ], + 'processors' => $processors, ], - - 'handlers' => [ - 'shlink_rotating_handler' => [ - 'class' => RotatingFileHandler::class, - 'level' => Logger::INFO, - 'filename' => 'data/log/shlink_log.log', - 'max_files' => 30, - 'formatter' => 'dashed', - ], - 'access_handler' => [ - 'class' => StreamHandler::class, - 'level' => Logger::INFO, - 'stream' => 'php://stdout', - ], - ], - - 'processors' => [ - 'exception_with_new_line' => [ - 'class' => Common\Logger\Processor\ExceptionWithNewLineProcessor::class, - ], - 'psr3' => [ - 'class' => Processor\PsrLogMessageProcessor::class, - ], - ], - - 'loggers' => [ - 'Shlink' => [ - 'handlers' => ['shlink_rotating_handler'], - 'processors' => ['exception_with_new_line', 'psr3'], - ], - 'Access' => [ - 'handlers' => ['access_handler'], - 'processors' => ['exception_with_new_line', 'psr3'], + 'Access' => [ + 'name' => 'Access', + 'handlers' => [ + 'access_handler' => [ + 'name' => Handler\StreamHandler::class, + 'params' => [ + 'level' => Logger::INFO, + 'stream' => 'php://stdout', + ], + 'formatter' => $formatter, + ], ], + 'processors' => $processors, ], ], 'dependencies' => [ 'factories' => [ - 'Logger_Shlink' => Common\Logger\LoggerFactory::class, - 'Logger_Access' => Common\Logger\LoggerFactory::class, + 'Logger_Shlink' => [DiContainerLoggerFactory::class, 'Shlink'], + 'Logger_Access' => [DiContainerLoggerFactory::class, 'Access'], ], 'aliases' => [ 'logger' => 'Logger_Shlink', diff --git a/config/autoload/logger.local.php.dist b/config/autoload/logger.local.php.dist index cf7e4801..4aa46c68 100644 --- a/config/autoload/logger.local.php.dist +++ b/config/autoload/logger.local.php.dist @@ -1,4 +1,5 @@ [ - 'shlink_rotating_handler' => [ - 'level' => Logger::EMERGENCY, // This basically disables regular file logs - ], - 'shlink_stdout_handler' => [ - 'class' => StreamHandler::class, +$handler = $isSwoole + ? [ + 'name' => StreamHandler::class, + 'params' => [ 'level' => Logger::DEBUG, 'stream' => 'php://stdout', - 'formatter' => 'dashed', ], - ], - - 'loggers' => [ - 'Shlink' => [ - 'handlers' => ['shlink_stdout_handler'], - ], - ], -] : [ - 'handlers' => [ - 'shlink_rotating_handler' => [ + ] + : [ + 'params' => [ 'level' => Logger::DEBUG, ], - ], -]; + ]; return [ - 'logger' => $logger, + 'logger' => [ + 'Shlink' => [ + 'handlers' => [ + 'shlink_handler' => $handler, + ], + ], + ], ]; diff --git a/config/autoload/middleware-pipeline.global.php b/config/autoload/middleware-pipeline.global.php index f9af01e3..35a9a16b 100644 --- a/config/autoload/middleware-pipeline.global.php +++ b/config/autoload/middleware-pipeline.global.php @@ -5,18 +5,31 @@ declare(strict_types=1); namespace Shlinkio\Shlink; use Zend\Expressive; +use Zend\ProblemDetails; use Zend\Stratigility\Middleware\ErrorHandler; return [ 'middleware_pipeline' => [ + 'error-handler' => [ + 'middleware' => [ + Expressive\Helper\ContentLengthMiddleware::class, + ErrorHandler::class, + ], + ], + 'error-handler-rest' => [ + 'path' => '/rest', + 'middleware' => [ + Rest\Middleware\CrossDomainMiddleware::class, + Rest\Middleware\BackwardsCompatibleProblemDetailsMiddleware::class, + ProblemDetails\ProblemDetailsMiddleware::class, + ], + ], + 'pre-routing' => [ 'middleware' => [ - ErrorHandler::class, - Expressive\Helper\ContentLengthMiddleware::class, Common\Middleware\CloseDbConnectionMiddleware::class, ], - 'priority' => 12, ], 'pre-routing-rest' => [ 'path' => '/rest', @@ -24,33 +37,40 @@ return [ Rest\Middleware\PathVersionMiddleware::class, Rest\Middleware\ShortUrl\ShortCodePathMiddleware::class, ], - 'priority' => 11, ], 'routing' => [ 'middleware' => [ Expressive\Router\Middleware\RouteMiddleware::class, ], - 'priority' => 10, ], 'rest' => [ 'path' => '/rest', 'middleware' => [ - Rest\Middleware\CrossDomainMiddleware::class, Expressive\Router\Middleware\ImplicitOptionsMiddleware::class, Rest\Middleware\BodyParserMiddleware::class, Rest\Middleware\AuthenticationMiddleware::class, ], - 'priority' => 5, ], - 'post-routing' => [ + 'dispatch' => [ 'middleware' => [ Expressive\Router\Middleware\DispatchMiddleware::class, - Core\Response\NotFoundHandler::class, ], - 'priority' => 1, + ], + + 'not-found-rest' => [ + 'path' => '/rest', + 'middleware' => [ + ProblemDetails\ProblemDetailsNotFoundHandler::class, + ], + ], + 'not-found' => [ + 'middleware' => [ + Core\ErrorHandler\NotFoundRedirectHandler::class, + Core\ErrorHandler\NotFoundTemplateHandler::class, + ], ], ], ]; diff --git a/config/autoload/url-shortener.global.php b/config/autoload/url-shortener.global.php index 7c7e19de..58bc3faa 100644 --- a/config/autoload/url-shortener.global.php +++ b/config/autoload/url-shortener.global.php @@ -2,16 +2,15 @@ declare(strict_types=1); -use function Shlinkio\Shlink\Common\env; - return [ 'url_shortener' => [ 'domain' => [ - 'schema' => env('SHORTENED_URL_SCHEMA', 'http'), - 'hostname' => env('SHORTENED_URL_HOSTNAME'), + 'schema' => 'https', + 'hostname' => '', ], 'validate_url' => true, + 'visits_webhooks' => [], ], ]; diff --git a/config/autoload/url-shortener.local.php.dist b/config/autoload/url-shortener.local.php.dist new file mode 100644 index 00000000..c686137f --- /dev/null +++ b/config/autoload/url-shortener.local.php.dist @@ -0,0 +1,14 @@ + [ + 'domain' => [ + 'schema' => 'http', + 'hostname' => 'localhost:8080', + ], + ], + +]; diff --git a/config/config.php b/config/config.php index 352a27ca..ad18fd20 100644 --- a/config/config.php +++ b/config/config.php @@ -4,9 +4,9 @@ declare(strict_types=1); namespace Shlinkio\Shlink; -use Acelaya\ExpressiveErrorHandler; use Zend\ConfigAggregator; use Zend\Expressive; +use Zend\ProblemDetails; use function Shlinkio\Shlink\Common\env; @@ -16,7 +16,7 @@ return (new ConfigAggregator\ConfigAggregator([ Expressive\Router\FastRouteRouter\ConfigProvider::class, Expressive\Plates\ConfigProvider::class, Expressive\Swoole\ConfigProvider::class, - ExpressiveErrorHandler\ConfigProvider::class, + ProblemDetails\ConfigProvider::class, Common\ConfigProvider::class, IpGeolocation\ConfigProvider::class, Core\ConfigProvider::class, diff --git a/config/container.php b/config/container.php index d33149a3..2ea9dc06 100644 --- a/config/container.php +++ b/config/container.php @@ -2,7 +2,6 @@ declare(strict_types=1); -use Symfony\Component\Dotenv\Dotenv; use Symfony\Component\Lock; use Zend\ServiceManager\ServiceManager; @@ -10,19 +9,16 @@ chdir(dirname(__DIR__)); require 'vendor/autoload.php'; -// If the Dotenv class exists, load env vars and enable errors -if (class_exists(Dotenv::class)) { - error_reporting(E_ALL); - ini_set('display_errors', '1'); - $dotenv = new Dotenv(); - $dotenv->load(__DIR__ . '/../.env'); +// This class alias tricks the ConfigAbstractFactory to return Lock\Factory instances even with a different service name +if (! class_exists('Shlinkio\Shlink\LocalLockFactory')) { + class_alias(Lock\LockFactory::class, 'Shlinkio\Shlink\LocalLockFactory'); } -// This class alias tricks the ConfigAbstractFactory to return Lock\Factory instances even with a different service name -class_alias(Lock\Factory::class, 'Shlinkio\Shlink\LocalLockFactory'); - // Build container -$config = require __DIR__ . '/config.php'; -$container = new ServiceManager($config['dependencies']); -$container->setService('config', $config); -return $container; +return (function () { + $config = require __DIR__ . '/config.php'; + $container = new ServiceManager($config['dependencies']); + $container->setService('config', $config); + + return $container; +})(); diff --git a/config/run.php b/config/run.php new file mode 100644 index 00000000..4ea61775 --- /dev/null +++ b/config/run.php @@ -0,0 +1,15 @@ +get($isCli ? CliApp::class : Application::class); + + $app->run(); +}; diff --git a/config/test/bootstrap_api_tests.php b/config/test/bootstrap_api_tests.php index 562986c1..3605427c 100644 --- a/config/test/bootstrap_api_tests.php +++ b/config/test/bootstrap_api_tests.php @@ -7,14 +7,6 @@ namespace Shlinkio\Shlink\TestUtils; use Doctrine\ORM\EntityManager; use Psr\Container\ContainerInterface; -use function file_exists; -use function touch; - -// Create an empty .env file -if (! file_exists('.env')) { - touch('.env'); -} - /** @var ContainerInterface $container */ $container = require __DIR__ . '/../container.php'; $testHelper = $container->get(Helper\TestHelper::class); diff --git a/config/test/bootstrap_db_tests.php b/config/test/bootstrap_db_tests.php index e5e88e20..9f14c38d 100644 --- a/config/test/bootstrap_db_tests.php +++ b/config/test/bootstrap_db_tests.php @@ -6,14 +6,6 @@ namespace Shlinkio\Shlink\TestUtils; use Psr\Container\ContainerInterface; -use function file_exists; -use function touch; - -// Create an empty .env file -if (! file_exists('.env')) { - touch('.env'); -} - /** @var ContainerInterface $container */ $container = require __DIR__ . '/../container.php'; $container->get(Helper\TestHelper::class)->createTestDb(); diff --git a/data/infra/php.ini b/data/infra/php.ini index 9c1e3f01..5ef7b7ea 100644 --- a/data/infra/php.ini +++ b/data/infra/php.ini @@ -1 +1,6 @@ -date.timezone = Europe/Madrid +display_errors=On +error_reporting=-1 +memory_limit=-1 +log_errors_max_len=0 +zend.assertions=1 +assert.exception=1 diff --git a/docker-compose.yml b/docker-compose.yml index 811eec69..99cc93fb 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -3,7 +3,7 @@ version: '3' services: shlink_nginx: container_name: shlink_nginx - image: nginx:1.15.9-alpine + image: nginx:1.17.6-alpine ports: - "8000:80" volumes: @@ -37,6 +37,7 @@ services: - "9001:9001" volumes: - ./:/home/shlink + - ./data/infra/php.ini:/usr/local/etc/php/php.ini links: - shlink_db - shlink_db_postgres diff --git a/docker/README.md b/docker/README.md index 32451338..b600c268 100644 --- a/docker/README.md +++ b/docker/README.md @@ -19,7 +19,7 @@ It also expects these two env vars to be provided, in order to properly generate So based on this, to run shlink on a local docker service, you should run a command like this: ```bash -docker run --name shlink -p 8080:8080 -e SHORT_DOMAIN_HOST=doma.in -e SHORT_DOMAIN_SCHEMA=https shlinkio/shlink +docker run --name shlink -p 8080:8080 -e SHORT_DOMAIN_HOST=doma.in -e SHORT_DOMAIN_SCHEMA=https shlinkio/shlink:stable ``` ### Interact with shlink's CLI on a running container. @@ -73,13 +73,13 @@ It is possible to use a set of env vars to make this shlink instance interact wi Taking this into account, you could run shlink on a local docker service like this: ```bash -docker run --name shlink -p 8080:8080 -e SHORT_DOMAIN_HOST=doma.in -e SHORT_DOMAIN_SCHEMA=https -e DB_DRIVER=mysql -e DB_USER=root -e DB_PASSWORD=123abc -e DB_HOST=something.rds.amazonaws.com shlinkio/shlink +docker run --name shlink -p 8080:8080 -e SHORT_DOMAIN_HOST=doma.in -e SHORT_DOMAIN_SCHEMA=https -e DB_DRIVER=mysql -e DB_USER=root -e DB_PASSWORD=123abc -e DB_HOST=something.rds.amazonaws.com shlinkio/shlink:stable ``` You could even link to a local database running on a different container: ```bash -docker run --name shlink -p 8080:8080 [...] -e DB_HOST=some_mysql_container --link some_mysql_container shlinkio/shlink +docker run --name shlink -p 8080:8080 [...] -e DB_HOST=some_mysql_container --link some_mysql_container shlinkio/shlink:stable ``` > If you have considered using SQLite but sharing the database file with a volume, read [this issue](https://github.com/shlinkio/shlink-docker-image/issues/40) first. @@ -110,6 +110,7 @@ This is the complete list of supported env vars: * `BASE_PATH`: The base path from which you plan to serve shlink, in case you don't want to serve it from the root of the domain. Defaults to `''`. * `WEB_WORKER_NUM`: The amount of concurrent http requests this shlink instance will be able to server. Defaults to 16. * `TASK_WORKER_NUM`: The amount of concurrent background tasks this shlink instance will be able to execute. Defaults to 16. +* `VISITS_WEBHOOKS`: A comma-separated list of URLs that will receive a `POST` request when a short URL receives a visit. * `REDIS_SERVERS`: A comma-separated list of redis servers where Shlink locks are stored (locks are used to prevent some operations to be run more than once in parallel). This is important when running more than one Shlink instance ([Multi instance considerations](#multi-instance-considerations)). If not provided, Shlink stores locks on every instance separately. @@ -145,7 +146,8 @@ docker run \ -e "BASE_PATH=/my-campaign" \ -e WEB_WORKER_NUM=64 \ -e TASK_WORKER_NUM=32 \ - shlinkio/shlink + -e "VISITS_WEBHOOKS=http://my-api.com/api/v2.3/notify,https://third-party.io/foo" \ + shlinkio/shlink:stable ``` ## Provide config via volumes @@ -173,6 +175,10 @@ The whole configuration should have this format, but it can be split into multip "tcp://172.20.0.1:6379", "tcp://172.20.0.2:6379" ], + "visits_webhooks": [ + "http://my-api.com/api/v2.3/notify", + "https://third-party.io/foo" + ], "db_config": { "driver": "pdo_mysql", "dbname": "shlink", @@ -192,7 +198,7 @@ The whole configuration should have this format, but it can be split into multip Once created just run shlink with the volume: ```bash -docker run --name shlink -p 8080:8080 -v ${PWD}/my/config/dir:/etc/shlink/config/params shlinkio/shlink +docker run --name shlink -p 8080:8080 -v ${PWD}/my/config/dir:/etc/shlink/config/params shlinkio/shlink:stable ``` ## Multi instance considerations diff --git a/docker/config/php.ini b/docker/config/php.ini new file mode 100644 index 00000000..f6c718d0 --- /dev/null +++ b/docker/config/php.ini @@ -0,0 +1,3 @@ +log_errors_max_len=0 +zend.assertions=1 +assert.exception=1 diff --git a/docker/config/shlink_in_docker.local.php b/docker/config/shlink_in_docker.local.php index bd2d0411..6d3367ac 100644 --- a/docker/config/shlink_in_docker.local.php +++ b/docker/config/shlink_in_docker.local.php @@ -99,6 +99,12 @@ $helper = new class { 'base_url' => env('BASE_URL_REDIRECT_TO'), ]; } + + public function getVisitsWebhooks(): array + { + $webhooks = env('VISITS_WEBHOOKS'); + return $webhooks === null ? [] : explode(',', $webhooks); + } }; return [ @@ -125,26 +131,21 @@ return [ 'hostname' => env('SHORT_DOMAIN_HOST', ''), ], 'validate_url' => (bool) env('VALIDATE_URLS', true), + 'visits_webhooks' => $helper->getVisitsWebhooks(), ], 'not_found_redirects' => $helper->getNotFoundRedirectsConfig(), 'logger' => [ - 'handlers' => [ - 'shlink_rotating_handler' => [ - 'level' => Logger::EMERGENCY, // This basically disables regular file logs - ], - 'shlink_stdout_handler' => [ - 'class' => StreamHandler::class, - 'level' => Logger::INFO, - 'stream' => 'php://stdout', - 'formatter' => 'dashed', - ], - ], - - 'loggers' => [ - 'Shlink' => [ - 'handlers' => ['shlink_stdout_handler'], + 'Shlink' => [ + 'handlers' => [ + 'shlink_handler' => [ + 'name' => StreamHandler::class, + 'params' => [ + 'level' => Logger::INFO, + 'stream' => 'php://stdout', + ], + ], ], ], ], diff --git a/docs/swagger/definitions/Error.json b/docs/swagger/definitions/Error.json index 3585227d..006fa47a 100644 --- a/docs/swagger/definitions/Error.json +++ b/docs/swagger/definitions/Error.json @@ -1,13 +1,32 @@ { "type": "object", + "required": ["type", "title", "detail", "status"], "properties": { - "code": { + "type": { "type": "string", "description": "A machine unique code" }, + "title": { + "type": "string", + "description": "A unique title" + }, + "detail": { + "type": "string", + "description": "A human-friendly error description" + }, + "status": { + "type": "number", + "description": "HTTP response status code" + }, + "code": { + "type": "string", + "description": "**[Deprecated] Use type instead. Not returned for v2 of the REST API** A machine unique code", + "deprecated": true + }, "message": { "type": "string", - "description": "A human-friendly error message" + "description": "**[Deprecated] Use detail instead. Not returned for v2 of the REST API** A human-friendly error message", + "deprecated": true } } } diff --git a/docs/swagger/parameters/version.json b/docs/swagger/parameters/version.json new file mode 100644 index 00000000..c2b1cc1a --- /dev/null +++ b/docs/swagger/parameters/version.json @@ -0,0 +1,13 @@ +{ + "name": "version", + "description": "The API version to be consumed", + "in": "path", + "required": true, + "schema": { + "type": "string", + "enum": [ + "2", + "1" + ] + } +} diff --git a/docs/swagger/paths/v1_short-urls.json b/docs/swagger/paths/v1_short-urls.json index f8fa1ec8..46708e22 100644 --- a/docs/swagger/paths/v1_short-urls.json +++ b/docs/swagger/paths/v1_short-urls.json @@ -7,6 +7,9 @@ "summary": "List short URLs", "description": "Returns the list of short URLs.

**Important note**: Before shlink v1.13, this endpoint used to use the `/short-codes` path instead of `/short-urls`. Both of them will keep working, while the first one is considered deprecated.", "parameters": [ + { + "$ref": "../parameters/version.json" + }, { "name": "page", "in": "query", @@ -51,6 +54,24 @@ "visits" ] } + }, + { + "name": "startDate", + "in": "query", + "description": "The date (in ISO-8601 format) from which we want to get short URLs.", + "required": false, + "schema": { + "type": "string" + } + }, + { + "name": "endDate", + "in": "query", + "description": "The date (in ISO-8601 format) until which we want to get short URLs.", + "required": false, + "schema": { + "type": "string" + } } ], "security": [ @@ -150,7 +171,7 @@ "500": { "description": "Unexpected error.", "content": { - "application/json": { + "application/problem+json": { "schema": { "$ref": "../definitions/Error.json" } @@ -175,6 +196,11 @@ "Bearer": [] } ], + "parameters": [ + { + "$ref": "../parameters/version.json" + } + ], "requestBody": { "description": "Request body.", "required": true, @@ -256,11 +282,43 @@ } }, "400": { - "description": "The long URL was not provided or is invalid.", + "description": "Some of provided data is invalid. Check extra fields to know exactly what.", "content": { - "application/json": { + "application/problem+json": { "schema": { - "$ref": "../definitions/Error.json" + "type": "object", + "allOf": [ + { + "$ref": "../definitions/Error.json" + }, + { + "type": "object", + "properties": { + "invalidElements": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "validSince", + "validUntil", + "customSlug", + "maxVisits", + "findIfExists", + "domain" + ] + } + }, + "url": { + "type": "string", + "description": "A URL that could not be verified, if the error type is INVALID_URL" + }, + "customSlug": { + "type": "string", + "description": "Provided custom slug when the error type is INVALID_SLUG" + } + } + } + ] } } } @@ -268,7 +326,7 @@ "500": { "description": "Unexpected error.", "content": { - "application/json": { + "application/problem+json": { "schema": { "$ref": "../definitions/Error.json" } diff --git a/docs/swagger/paths/v1_short-urls_shorten.json b/docs/swagger/paths/v1_short-urls_shorten.json index 803d77d5..49233c49 100644 --- a/docs/swagger/paths/v1_short-urls_shorten.json +++ b/docs/swagger/paths/v1_short-urls_shorten.json @@ -7,6 +7,9 @@ "summary": "Create a short URL", "description": "Creates a short URL in a single API call. Useful for third party integrations.

**Important note**: Before shlink v1.13, this endpoint used to use the `/short-codes` path instead of `/short-urls`. Both of them will keep working, while the first one is considered deprecated.", "parameters": [ + { + "$ref": "../parameters/version.json" + }, { "name": "apiKey", "in": "query", @@ -77,7 +80,7 @@ "400": { "description": "The long URL was not provided or is invalid.", "content": { - "application/json": { + "application/problem+json": { "schema": { "$ref": "../definitions/Error.json" } @@ -89,9 +92,12 @@ } }, "examples": { - "application/json": { - "error": "INVALID_URL", - "message": "Provided URL foo is invalid. Try with a different one." + "application/problem+json": { + "title": "Invalid URL", + "type": "INVALID_URL", + "detail": "Provided URL foo is invalid. Try with a different one.", + "status": 400, + "url": "https://invalid-url.com" }, "text/plain": "INVALID_URL" } @@ -99,7 +105,7 @@ "500": { "description": "Unexpected error.", "content": { - "application/json": { + "application/problem+json": { "schema": { "$ref": "../definitions/Error.json" } @@ -111,11 +117,11 @@ } }, "examples": { - "application/json": { - "error": "UNKNOWN_ERROR", + "application/problem+json": { + "error": "INTERNAL_SERVER_ERROR", "message": "Unexpected error occurred" }, - "text/plain": "UNKNOWN_ERROR" + "text/plain": "INTERNAL_SERVER_ERROR" } } } diff --git a/docs/swagger/paths/v1_short-urls_{shortCode}.json b/docs/swagger/paths/v1_short-urls_{shortCode}.json index bbb7145c..95532868 100644 --- a/docs/swagger/paths/v1_short-urls_{shortCode}.json +++ b/docs/swagger/paths/v1_short-urls_{shortCode}.json @@ -7,6 +7,9 @@ "summary": "Parse short code", "description": "Get the long URL behind a short URL's short code.

**Important note**: Before shlink v1.13, this endpoint used to use the `/short-codes` path instead of `/short-urls`. Both of them will keep working, while the first one is considered deprecated.", "parameters": [ + { + "$ref": "../parameters/version.json" + }, { "name": "shortCode", "in": "path", @@ -62,20 +65,10 @@ } } }, - "400": { - "description": "Provided shortCode does not match the character set currently used by the app to generate short codes.", - "content": { - "application/json": { - "schema": { - "$ref": "../definitions/Error.json" - } - } - } - }, "404": { "description": "No URL was found for provided short code.", "content": { - "application/json": { + "application/problem+json": { "schema": { "$ref": "../definitions/Error.json" } @@ -85,7 +78,7 @@ "500": { "description": "Unexpected error.", "content": { - "application/json": { + "application/problem+json": { "schema": { "$ref": "../definitions/Error.json" } @@ -103,6 +96,9 @@ "summary": "Edit short URL", "description": "Update certain meta arguments from an existing short URL.

**Important note**: Before shlink v1.13, this endpoint used to use the `/short-codes` path instead of `/short-urls`. Both of them will keep working, while the first one is considered deprecated.", "parameters": [ + { + "$ref": "../parameters/version.json" + }, { "name": "shortCode", "in": "path", @@ -153,9 +149,31 @@ "400": { "description": "Provided meta arguments are invalid.", "content": { - "application/json": { + "application/problem+json": { "schema": { - "$ref": "../definitions/Error.json" + "type": "object", + "allOf": [ + { + "$ref": "../definitions/Error.json" + }, + { + "type": "object", + "required": ["invalidElements"], + "properties": { + "invalidElements": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "validSince", + "validUntil", + "maxVisits" + ] + } + } + } + } + ] } } } @@ -163,7 +181,7 @@ "404": { "description": "No short URL was found for provided short code.", "content": { - "application/json": { + "application/problem+json": { "schema": { "$ref": "../definitions/Error.json" } @@ -173,7 +191,7 @@ "500": { "description": "Unexpected error.", "content": { - "application/json": { + "application/problem+json": { "schema": { "$ref": "../definitions/Error.json" } @@ -192,6 +210,9 @@ "summary": "[DEPRECATED] Edit short URL", "description": "**[DEPRECATED]** Use [editShortUrl](#/Short_URLs/getShortUrl) instead", "parameters": [ + { + "$ref": "../parameters/version.json" + }, { "name": "shortCode", "in": "path", @@ -242,7 +263,7 @@ "400": { "description": "Provided meta arguments are invalid.", "content": { - "application/json": { + "application/problem+json": { "schema": { "$ref": "../definitions/Error.json" } @@ -252,7 +273,7 @@ "404": { "description": "No short URL was found for provided short code.", "content": { - "application/json": { + "application/problem+json": { "schema": { "$ref": "../definitions/Error.json" } @@ -262,7 +283,7 @@ "500": { "description": "Unexpected error.", "content": { - "application/json": { + "application/problem+json": { "schema": { "$ref": "../definitions/Error.json" } @@ -280,6 +301,9 @@ "summary": "Delete short URL", "description": "Deletes the short URL for provided short code.

**Important note**: Before shlink v1.13, this endpoint used to use the `/short-codes` path instead of `/short-urls`. Both of them will keep working, while the first one is considered deprecated.", "parameters": [ + { + "$ref": "../parameters/version.json" + }, { "name": "shortCode", "in": "path", @@ -302,26 +326,28 @@ "204": { "description": "The short URL has been properly deleted." }, - "400": { + "422": { "description": "The visits threshold in shlink does not allow this short URL to be deleted.", "content": { - "application/json": { + "application/problem+json": { "schema": { "$ref": "../definitions/Error.json" } } }, "examples": { - "application/json": { - "error": "INVALID_SHORTCODE_DELETION", - "message": "It is not possible to delete URL with short code \"abc123\" because it has reached more than \"15\" visits." + "application/problem+json": { + "title": "Cannot delete short URL", + "type": "INVALID_SHORTCODE_DELETION", + "detail": "It is not possible to delete URL with short code \"abc123\" because it has reached more than \"15\" visits.", + "status": 422 } } }, "404": { "description": "No short URL was found for provided short code.", "content": { - "application/json": { + "application/problem+json": { "schema": { "$ref": "../definitions/Error.json" } @@ -331,7 +357,7 @@ "500": { "description": "Unexpected error.", "content": { - "application/json": { + "application/problem+json": { "schema": { "$ref": "../definitions/Error.json" } diff --git a/docs/swagger/paths/v1_short-urls_{shortCode}_tags.json b/docs/swagger/paths/v1_short-urls_{shortCode}_tags.json index ab05d230..45142e62 100644 --- a/docs/swagger/paths/v1_short-urls_{shortCode}_tags.json +++ b/docs/swagger/paths/v1_short-urls_{shortCode}_tags.json @@ -7,6 +7,9 @@ "summary": "Edit tags on short URL", "description": "Edit the tags on URL identified by provided short code.

**Important note**: Before shlink v1.13, this endpoint used to use the `/short-codes` path instead of `/short-urls`. Both of them will keep working, while the first one is considered deprecated.", "parameters": [ + { + "$ref": "../parameters/version.json" + }, { "name": "shortCode", "in": "path", @@ -78,7 +81,7 @@ "400": { "description": "The request body does not contain a \"tags\" param with array type.", "content": { - "application/json": { + "application/problem+json": { "schema": { "$ref": "../definitions/Error.json" } diff --git a/docs/swagger/paths/v1_short-urls_{shortCode}_visits.json b/docs/swagger/paths/v1_short-urls_{shortCode}_visits.json index a3cf5f10..508449de 100644 --- a/docs/swagger/paths/v1_short-urls_{shortCode}_visits.json +++ b/docs/swagger/paths/v1_short-urls_{shortCode}_visits.json @@ -7,6 +7,9 @@ "summary": "List visits for short URL", "description": "Get the list of visits on the short URL behind provided short code.

**Important note**: Before shlink v1.13, this endpoint used to use the `/short-codes` path instead of `/short-urls`. Both of them will keep working, while the first one is considered deprecated.", "parameters": [ + { + "$ref": "../parameters/version.json" + }, { "name": "shortCode", "in": "path", @@ -132,7 +135,7 @@ "404": { "description": "The short code does not belong to any short URL.", "content": { - "application/json": { + "application/problem+json": { "schema": { "$ref": "../definitions/Error.json" } @@ -142,7 +145,7 @@ "500": { "description": "Unexpected error.", "content": { - "application/json": { + "application/problem+json": { "schema": { "$ref": "../definitions/Error.json" } diff --git a/docs/swagger/paths/v1_tags.json b/docs/swagger/paths/v1_tags.json index 5bf260bb..a0fcc512 100644 --- a/docs/swagger/paths/v1_tags.json +++ b/docs/swagger/paths/v1_tags.json @@ -14,6 +14,11 @@ "Bearer": [] } ], + "parameters": [ + { + "$ref": "../parameters/version.json" + } + ], "responses": { "200": { "description": "The list of tags", @@ -53,7 +58,7 @@ "500": { "description": "Unexpected error.", "content": { - "application/json": { + "application/problem+json": { "schema": { "$ref": "../definitions/Error.json" } @@ -78,6 +83,11 @@ "Bearer": [] } ], + "parameters": [ + { + "$ref": "../parameters/version.json" + } + ], "requestBody": { "description": "Request body.", "required": true, @@ -140,7 +150,7 @@ "500": { "description": "Unexpected error.", "content": { - "application/json": { + "application/problem+json": { "schema": { "$ref": "../definitions/Error.json" } @@ -165,6 +175,11 @@ "Bearer": [] } ], + "parameters": [ + { + "$ref": "../parameters/version.json" + } + ], "requestBody": { "description": "Request body.", "required": true, @@ -197,7 +212,7 @@ "400": { "description": "You have not provided either the oldName or the newName params.", "content": { - "application/json": { + "application/problem+json": { "schema": { "$ref": "../definitions/Error.json" } @@ -207,7 +222,17 @@ "404": { "description": "There's no tag found with the name provided in oldName param.", "content": { - "application/json": { + "application/problem+json": { + "schema": { + "$ref": "../definitions/Error.json" + } + } + } + }, + "409": { + "description": "The name provided in newName param is already in use for another tag.", + "content": { + "application/problem+json": { "schema": { "$ref": "../definitions/Error.json" } @@ -217,7 +242,7 @@ "500": { "description": "Unexpected error.", "content": { - "application/json": { + "application/problem+json": { "schema": { "$ref": "../definitions/Error.json" } @@ -235,6 +260,9 @@ "summary": "Delete tags", "description": "Deletes provided list of tags", "parameters": [ + { + "$ref": "../parameters/version.json" + }, { "name": "tags[]", "in": "query", @@ -263,7 +291,7 @@ "500": { "description": "Unexpected error.", "content": { - "application/json": { + "application/problem+json": { "schema": { "$ref": "../definitions/Error.json" } diff --git a/docs/swagger/paths/{shortCode}.json b/docs/swagger/paths/{shortCode}.json index eccd5ba1..bbebacbd 100644 --- a/docs/swagger/paths/{shortCode}.json +++ b/docs/swagger/paths/{shortCode}.json @@ -20,16 +20,6 @@ "responses": { "302": { "description": "Visit properly tracked and redirected" - }, - "500": { - "description": "Unexpected error.", - "content": { - "application/json": { - "schema": { - "$ref": "../definitions/Error.json" - } - } - } } } } diff --git a/docs/swagger/paths/{shortCode}_preview.json b/docs/swagger/paths/{shortCode}_preview.json index f6168b4d..98df559c 100644 --- a/docs/swagger/paths/{shortCode}_preview.json +++ b/docs/swagger/paths/{shortCode}_preview.json @@ -29,16 +29,6 @@ } } } - }, - "500": { - "description": "Unexpected error.", - "content": { - "application/json": { - "schema": { - "$ref": "../definitions/Error.json" - } - } - } } } } diff --git a/docs/swagger/paths/{shortCode}_qr-code.json b/docs/swagger/paths/{shortCode}_qr-code.json index 14a8fddc..300a7429 100644 --- a/docs/swagger/paths/{shortCode}_qr-code.json +++ b/docs/swagger/paths/{shortCode}_qr-code.json @@ -40,16 +40,6 @@ } } } - }, - "500": { - "description": "Unexpected error.", - "content": { - "application/json": { - "schema": { - "$ref": "../definitions/Error.json" - } - } - } } } } diff --git a/docs/swagger/paths/{shortCode}_track.json b/docs/swagger/paths/{shortCode}_track.json index b4b62bba..50f6bc5e 100644 --- a/docs/swagger/paths/{shortCode}_track.json +++ b/docs/swagger/paths/{shortCode}_track.json @@ -28,16 +28,6 @@ } } } - }, - "500": { - "description": "Unexpected error.", - "content": { - "application/json": { - "schema": { - "$ref": "../definitions/Error.json" - } - } - } } } } diff --git a/docs/swagger/swagger.json b/docs/swagger/swagger.json index 6dd3ff8f..d924b8a0 100644 --- a/docs/swagger/swagger.json +++ b/docs/swagger/swagger.json @@ -71,24 +71,24 @@ ], "paths": { - "/rest/v1/short-urls": { + "/rest/v{version}/short-urls": { "$ref": "paths/v1_short-urls.json" }, - "/rest/v1/short-urls/shorten": { + "/rest/v{version}/short-urls/shorten": { "$ref": "paths/v1_short-urls_shorten.json" }, - "/rest/v1/short-urls/{shortCode}": { + "/rest/v{version}/short-urls/{shortCode}": { "$ref": "paths/v1_short-urls_{shortCode}.json" }, - "/rest/v1/short-urls/{shortCode}/tags": { + "/rest/v{version}/short-urls/{shortCode}/tags": { "$ref": "paths/v1_short-urls_{shortCode}_tags.json" }, - "/rest/v1/tags": { + "/rest/v{version}/tags": { "$ref": "paths/v1_tags.json" }, - "/rest/v1/short-urls/{shortCode}/visits": { + "/rest/v{version}/short-urls/{shortCode}/visits": { "$ref": "paths/v1_short-urls_{shortCode}_visits.json" }, diff --git a/hooks/build b/hooks/build index d7d39368..6b381d74 100755 --- a/hooks/build +++ b/hooks/build @@ -1,7 +1,7 @@ #!/bin/bash set -ex -if [[ ${SOURCE_BRANCH} == 'master' ]]; then +if [[ ${SOURCE_BRANCH} == 'develop' ]]; then SHLINK_RELEASE='latest' else SHLINK_RELEASE=${SOURCE_BRANCH#?} diff --git a/module/CLI/config/dependencies.config.php b/module/CLI/config/dependencies.config.php index a7f7e90e..c89a0ad7 100644 --- a/module/CLI/config/dependencies.config.php +++ b/module/CLI/config/dependencies.config.php @@ -15,7 +15,7 @@ use Shlinkio\Shlink\IpGeolocation\Resolver\IpLocationResolverInterface; use Shlinkio\Shlink\PreviewGenerator\Service\PreviewGenerator; use Shlinkio\Shlink\Rest\Service\ApiKeyService; use Symfony\Component\Console as SymfonyCli; -use Symfony\Component\Lock\Factory as Locker; +use Symfony\Component\Lock\LockFactory; use Symfony\Component\Process\PhpExecutableFinder; use Zend\ServiceManager\AbstractFactory\ConfigAbstractFactory; use Zend\ServiceManager\Factory\InvokableFactory; @@ -70,7 +70,7 @@ return [ Command\Visit\LocateVisitsCommand::class => [ Service\VisitService::class, IpLocationResolverInterface::class, - Locker::class, + LockFactory::class, GeolocationDbUpdater::class, ], Command\Visit\UpdateDbCommand::class => [DbUpdater::class], @@ -85,14 +85,14 @@ return [ Command\Tag\DeleteTagsCommand::class => [Service\Tag\TagService::class], Command\Db\CreateDatabaseCommand::class => [ - Locker::class, + LockFactory::class, SymfonyCli\Helper\ProcessHelper::class, PhpExecutableFinder::class, Connection::class, NoDbNameConnectionFactory::SERVICE_NAME, ], Command\Db\MigrateDatabaseCommand::class => [ - Locker::class, + LockFactory::class, SymfonyCli\Helper\ProcessHelper::class, PhpExecutableFinder::class, ], diff --git a/module/CLI/src/Command/Api/DisableKeyCommand.php b/module/CLI/src/Command/Api/DisableKeyCommand.php index e0f2b79c..f3eb7f6b 100644 --- a/module/CLI/src/Command/Api/DisableKeyCommand.php +++ b/module/CLI/src/Command/Api/DisableKeyCommand.php @@ -4,8 +4,8 @@ declare(strict_types=1); namespace Shlinkio\Shlink\CLI\Command\Api; -use InvalidArgumentException; use Shlinkio\Shlink\CLI\Util\ExitCodes; +use Shlinkio\Shlink\Common\Exception\InvalidArgumentException; use Shlinkio\Shlink\Rest\Service\ApiKeyServiceInterface; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; @@ -45,7 +45,7 @@ class DisableKeyCommand extends Command $io->success(sprintf('API key "%s" properly disabled', $apiKey)); return ExitCodes::EXIT_SUCCESS; } catch (InvalidArgumentException $e) { - $io->error(sprintf('API key "%s" does not exist.', $apiKey)); + $io->error($e->getMessage()); return ExitCodes::EXIT_FAILURE; } } diff --git a/module/CLI/src/Command/Api/GenerateKeyCommand.php b/module/CLI/src/Command/Api/GenerateKeyCommand.php index f35fa012..bbe86a51 100644 --- a/module/CLI/src/Command/Api/GenerateKeyCommand.php +++ b/module/CLI/src/Command/Api/GenerateKeyCommand.php @@ -36,7 +36,7 @@ class GenerateKeyCommand extends Command ->addOption( 'expirationDate', 'e', - InputOption::VALUE_OPTIONAL, + InputOption::VALUE_REQUIRED, 'The date in which the API key should expire. Use any valid PHP format.' ); } diff --git a/module/CLI/src/Command/Db/AbstractDatabaseCommand.php b/module/CLI/src/Command/Db/AbstractDatabaseCommand.php index 3ab12b3b..bf99de9b 100644 --- a/module/CLI/src/Command/Db/AbstractDatabaseCommand.php +++ b/module/CLI/src/Command/Db/AbstractDatabaseCommand.php @@ -8,7 +8,7 @@ use Shlinkio\Shlink\CLI\Command\Util\AbstractLockedCommand; use Shlinkio\Shlink\CLI\Command\Util\LockedCommandConfig; use Symfony\Component\Console\Helper\ProcessHelper; use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Lock\Factory as Locker; +use Symfony\Component\Lock\LockFactory; use Symfony\Component\Process\PhpExecutableFinder; use function array_unshift; @@ -20,7 +20,7 @@ abstract class AbstractDatabaseCommand extends AbstractLockedCommand /** @var string */ private $phpBinary; - public function __construct(Locker $locker, ProcessHelper $processHelper, PhpExecutableFinder $phpFinder) + public function __construct(LockFactory $locker, ProcessHelper $processHelper, PhpExecutableFinder $phpFinder) { parent::__construct($locker); $this->processHelper = $processHelper; diff --git a/module/CLI/src/Command/Db/CreateDatabaseCommand.php b/module/CLI/src/Command/Db/CreateDatabaseCommand.php index 36bb9de4..54cd27ea 100644 --- a/module/CLI/src/Command/Db/CreateDatabaseCommand.php +++ b/module/CLI/src/Command/Db/CreateDatabaseCommand.php @@ -10,7 +10,7 @@ use Symfony\Component\Console\Helper\ProcessHelper; 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 Symfony\Component\Lock\LockFactory; use Symfony\Component\Process\PhpExecutableFinder; use function Functional\contains; @@ -27,7 +27,7 @@ class CreateDatabaseCommand extends AbstractDatabaseCommand private $noDbNameConn; public function __construct( - Locker $locker, + LockFactory $locker, ProcessHelper $processHelper, PhpExecutableFinder $phpFinder, Connection $conn, diff --git a/module/CLI/src/Command/ShortUrl/DeleteShortUrlCommand.php b/module/CLI/src/Command/ShortUrl/DeleteShortUrlCommand.php index 683fd893..c2e81d0d 100644 --- a/module/CLI/src/Command/ShortUrl/DeleteShortUrlCommand.php +++ b/module/CLI/src/Command/ShortUrl/DeleteShortUrlCommand.php @@ -55,22 +55,17 @@ class DeleteShortUrlCommand extends Command try { $this->runDelete($io, $shortCode, $ignoreThreshold); return ExitCodes::EXIT_SUCCESS; - } catch (Exception\InvalidShortCodeException $e) { - $io->error(sprintf('Provided short code "%s" could not be found.', $shortCode)); + } catch (Exception\ShortUrlNotFoundException $e) { + $io->error($e->getMessage()); return ExitCodes::EXIT_FAILURE; } catch (Exception\DeleteShortUrlException $e) { - return $this->retry($io, $shortCode, $e); + return $this->retry($io, $shortCode, $e->getMessage()); } } - private function retry(SymfonyStyle $io, string $shortCode, Exception\DeleteShortUrlException $e): int + private function retry(SymfonyStyle $io, string $shortCode, string $warningMsg): int { - $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('' . $warningMsg . ''); + $io->writeln(sprintf('%s', $warningMsg)); $forceDelete = $io->confirm('Do you want to delete it anyway?', false); if ($forceDelete) { diff --git a/module/CLI/src/Command/ShortUrl/GeneratePreviewCommand.php b/module/CLI/src/Command/ShortUrl/GeneratePreviewCommand.php index 7483e890..081fa94f 100644 --- a/module/CLI/src/Command/ShortUrl/GeneratePreviewCommand.php +++ b/module/CLI/src/Command/ShortUrl/GeneratePreviewCommand.php @@ -69,7 +69,7 @@ class GeneratePreviewCommand extends Command } catch (PreviewGenerationException $e) { $output->writeln(' Error'); if ($output->isVerbose()) { - $this->getApplication()->renderException($e, $output); + $this->getApplication()->renderThrowable($e, $output); } } } diff --git a/module/CLI/src/Command/ShortUrl/GenerateShortUrlCommand.php b/module/CLI/src/Command/ShortUrl/GenerateShortUrlCommand.php index d7323a0d..faefbf4b 100644 --- a/module/CLI/src/Command/ShortUrl/GenerateShortUrlCommand.php +++ b/module/CLI/src/Command/ShortUrl/GenerateShortUrlCommand.php @@ -140,13 +140,8 @@ class GenerateShortUrlCommand extends Command sprintf('Generated short URL: %s', $shortUrl->toString($this->domainConfig)), ]); return ExitCodes::EXIT_SUCCESS; - } catch (InvalidUrlException $e) { - $io->error(sprintf('Provided URL "%s" is invalid. Try with a different one.', $longUrl)); - return ExitCodes::EXIT_FAILURE; - } catch (NonUniqueSlugException $e) { - $io->error( - sprintf('Provided slug "%s" is already in use by another URL. Try with a different one.', $customSlug) - ); + } catch (InvalidUrlException | NonUniqueSlugException $e) { + $io->error($e->getMessage()); return ExitCodes::EXIT_FAILURE; } } diff --git a/module/CLI/src/Command/ShortUrl/GetVisitsCommand.php b/module/CLI/src/Command/ShortUrl/GetVisitsCommand.php index 7873fba6..7a51ac0b 100644 --- a/module/CLI/src/Command/ShortUrl/GetVisitsCommand.php +++ b/module/CLI/src/Command/ShortUrl/GetVisitsCommand.php @@ -4,25 +4,22 @@ declare(strict_types=1); namespace Shlinkio\Shlink\CLI\Command\ShortUrl; -use Cake\Chronos\Chronos; +use Shlinkio\Shlink\CLI\Command\Util\AbstractWithDateRangeCommand; use Shlinkio\Shlink\CLI\Util\ExitCodes; use Shlinkio\Shlink\CLI\Util\ShlinkTable; use Shlinkio\Shlink\Common\Util\DateRange; use Shlinkio\Shlink\Core\Entity\Visit; use Shlinkio\Shlink\Core\Model\VisitsParams; use Shlinkio\Shlink\Core\Service\VisitsTrackerInterface; -use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; 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\Stdlib\ArrayUtils; -use function array_map; +use function Functional\map; use function Functional\select_keys; -class GetVisitsCommand extends Command +class GetVisitsCommand extends AbstractWithDateRangeCommand { public const NAME = 'short-url:visits'; private const ALIASES = ['shortcode:visits', 'short-code:visits']; @@ -36,25 +33,23 @@ class GetVisitsCommand extends Command parent::__construct(); } - protected function configure(): void + protected function doConfigure(): void { $this ->setName(self::NAME) ->setAliases(self::ALIASES) ->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, - 'Allows to filter visits, returning only those older than start date' - ) - ->addOption( - 'endDate', - 'e', - InputOption::VALUE_OPTIONAL, - 'Allows to filter visits, returning only those newer than end date' - ); + ->addArgument('shortCode', InputArgument::REQUIRED, 'The short code which visits we want to get'); + } + + protected function getStartDateDesc(): string + { + return 'Allows to filter visits, returning only those older than start date'; + } + + protected function getEndDateDesc(): string + { + return 'Allows to filter visits, returning only those newer than end date'; } protected function interact(InputInterface $input, OutputInterface $output): void @@ -74,24 +69,18 @@ class GetVisitsCommand extends Command protected function execute(InputInterface $input, OutputInterface $output): ?int { $shortCode = $input->getArgument('shortCode'); - $startDate = $this->getDateOption($input, 'startDate'); - $endDate = $this->getDateOption($input, 'endDate'); + $startDate = $this->getDateOption($input, $output, 'startDate'); + $endDate = $this->getDateOption($input, $output, 'endDate'); $paginator = $this->visitsTracker->info($shortCode, new VisitsParams(new DateRange($startDate, $endDate))); - $visits = ArrayUtils::iteratorToArray($paginator->getCurrentItems()); - $rows = array_map(function (Visit $visit) { + $rows = map($paginator->getCurrentItems(), function (Visit $visit) { $rowData = $visit->jsonSerialize(); $rowData['country'] = $visit->getVisitLocation()->getCountryName(); return select_keys($rowData, ['referer', 'date', 'userAgent', 'country']); - }, $visits); + }); ShlinkTable::fromOutput($output)->render(['Referer', 'Date', 'User agent', 'Country'], $rows); + return ExitCodes::EXIT_SUCCESS; } - - private function getDateOption(InputInterface $input, $key) - { - $value = $input->getOption($key); - return ! empty($value) ? Chronos::parse($value) : $value; - } } diff --git a/module/CLI/src/Command/ShortUrl/ListShortUrlsCommand.php b/module/CLI/src/Command/ShortUrl/ListShortUrlsCommand.php index 3d9b528d..01080189 100644 --- a/module/CLI/src/Command/ShortUrl/ListShortUrlsCommand.php +++ b/module/CLI/src/Command/ShortUrl/ListShortUrlsCommand.php @@ -4,14 +4,15 @@ declare(strict_types=1); namespace Shlinkio\Shlink\CLI\Command\ShortUrl; +use Cake\Chronos\Chronos; +use Shlinkio\Shlink\CLI\Command\Util\AbstractWithDateRangeCommand; use Shlinkio\Shlink\CLI\Util\ExitCodes; use Shlinkio\Shlink\CLI\Util\ShlinkTable; use Shlinkio\Shlink\Common\Paginator\Util\PaginatorUtilsTrait; -use Shlinkio\Shlink\Common\Rest\DataTransformerInterface; +use Shlinkio\Shlink\Common\Util\DateRange; use Shlinkio\Shlink\Core\Paginator\Adapter\ShortUrlRepositoryAdapter; use Shlinkio\Shlink\Core\Service\ShortUrlServiceInterface; use Shlinkio\Shlink\Core\Transformer\ShortUrlDataTransformer; -use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; @@ -26,7 +27,7 @@ use function explode; use function implode; use function sprintf; -class ListShortUrlsCommand extends Command +class ListShortUrlsCommand extends AbstractWithDateRangeCommand { use PaginatorUtilsTrait; @@ -43,17 +44,17 @@ class ListShortUrlsCommand extends Command /** @var ShortUrlServiceInterface */ private $shortUrlService; - /** @var array */ - private $domainConfig; + /** @var ShortUrlDataTransformer */ + private $transformer; public function __construct(ShortUrlServiceInterface $shortUrlService, array $domainConfig) { parent::__construct(); $this->shortUrlService = $shortUrlService; - $this->domainConfig = $domainConfig; + $this->transformer = new ShortUrlDataTransformer($domainConfig); } - protected function configure(): void + protected function doConfigure(): void { $this ->setName(self::NAME) @@ -68,7 +69,7 @@ class ListShortUrlsCommand extends Command ) ->addOption( 'searchTerm', - 's', + 'st', InputOption::VALUE_REQUIRED, 'A query used to filter results by searching for it on the longUrl and shortCode fields' ) @@ -87,18 +88,31 @@ class ListShortUrlsCommand extends Command ->addOption('showTags', null, InputOption::VALUE_NONE, 'Whether to display the tags or not'); } + protected function getStartDateDesc(): string + { + return 'Allows to filter short URLs, returning only those created after "startDate"'; + } + + protected function getEndDateDesc(): string + { + return 'Allows to filter short URLs, returning only those created before "endDate"'; + } + protected function execute(InputInterface $input, OutputInterface $output): ?int { $io = new SymfonyStyle($input, $output); + $page = (int) $input->getOption('page'); $searchTerm = $input->getOption('searchTerm'); $tags = $input->getOption('tags'); $tags = ! empty($tags) ? explode(',', $tags) : []; $showTags = (bool) $input->getOption('showTags'); - $transformer = new ShortUrlDataTransformer($this->domainConfig); + $startDate = $this->getDateOption($input, $output, 'startDate'); + $endDate = $this->getDateOption($input, $output, 'endDate'); + $orderBy = $this->processOrderBy($input); do { - $result = $this->renderPage($input, $output, $page, $searchTerm, $tags, $showTags, $transformer); + $result = $this->renderPage($output, $page, $searchTerm, $tags, $showTags, $startDate, $endDate, $orderBy); $page++; $continue = $this->isLastPage($result) @@ -108,19 +122,27 @@ class ListShortUrlsCommand extends Command $io->newLine(); $io->success('Short URLs properly listed'); + return ExitCodes::EXIT_SUCCESS; } private function renderPage( - InputInterface $input, OutputInterface $output, int $page, ?string $searchTerm, array $tags, bool $showTags, - DataTransformerInterface $transformer + ?Chronos $startDate, + ?Chronos $endDate, + $orderBy ): Paginator { - $result = $this->shortUrlService->listShortUrls($page, $searchTerm, $tags, $this->processOrderBy($input)); + $result = $this->shortUrlService->listShortUrls( + $page, + $searchTerm, + $tags, + $orderBy, + new DateRange($startDate, $endDate) + ); $headers = ['Short code', 'Short URL', 'Long URL', 'Date created', 'Visits count']; if ($showTags) { @@ -129,7 +151,7 @@ class ListShortUrlsCommand extends Command $rows = []; foreach ($result as $row) { - $shortUrl = $transformer->transform($row); + $shortUrl = $this->transformer->transform($row); if ($showTags) { $shortUrl['tags'] = implode(', ', $shortUrl['tags']); } else { @@ -143,9 +165,13 @@ class ListShortUrlsCommand extends Command $result, 'Page %s of %s' )); + return $result; } + /** + * @return array|string|null + */ private function processOrderBy(InputInterface $input) { $orderBy = $input->getOption('orderBy'); diff --git a/module/CLI/src/Command/ShortUrl/ResolveUrlCommand.php b/module/CLI/src/Command/ShortUrl/ResolveUrlCommand.php index bc159a79..e8db28e2 100644 --- a/module/CLI/src/Command/ShortUrl/ResolveUrlCommand.php +++ b/module/CLI/src/Command/ShortUrl/ResolveUrlCommand.php @@ -5,8 +5,7 @@ declare(strict_types=1); namespace Shlinkio\Shlink\CLI\Command\ShortUrl; use Shlinkio\Shlink\CLI\Util\ExitCodes; -use Shlinkio\Shlink\Core\Exception\EntityDoesNotExistException; -use Shlinkio\Shlink\Core\Exception\InvalidShortCodeException; +use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException; use Shlinkio\Shlink\Core\Service\UrlShortenerInterface; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; @@ -65,11 +64,8 @@ class ResolveUrlCommand extends Command $url = $this->urlShortener->shortCodeToUrl($shortCode, $domain); $output->writeln(sprintf('Long URL: %s', $url->getLongUrl())); return ExitCodes::EXIT_SUCCESS; - } catch (InvalidShortCodeException $e) { - $io->error(sprintf('Provided short code "%s" has an invalid format.', $shortCode)); - return ExitCodes::EXIT_FAILURE; - } catch (EntityDoesNotExistException $e) { - $io->error(sprintf('Provided short code "%s" could not be found.', $shortCode)); + } catch (ShortUrlNotFoundException $e) { + $io->error($e->getMessage()); return ExitCodes::EXIT_FAILURE; } } diff --git a/module/CLI/src/Command/Tag/RenameTagCommand.php b/module/CLI/src/Command/Tag/RenameTagCommand.php index 1638108a..d1607f34 100644 --- a/module/CLI/src/Command/Tag/RenameTagCommand.php +++ b/module/CLI/src/Command/Tag/RenameTagCommand.php @@ -5,8 +5,8 @@ declare(strict_types=1); namespace Shlinkio\Shlink\CLI\Command\Tag; use Shlinkio\Shlink\CLI\Util\ExitCodes; -use Shlinkio\Shlink\Core\Exception\EntityDoesNotExistException; use Shlinkio\Shlink\Core\Exception\TagConflictException; +use Shlinkio\Shlink\Core\Exception\TagNotFoundException; use Shlinkio\Shlink\Core\Service\Tag\TagServiceInterface; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; @@ -14,8 +14,6 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; -use function sprintf; - class RenameTagCommand extends Command { public const NAME = 'tag:rename'; @@ -48,13 +46,8 @@ class RenameTagCommand extends Command $this->tagService->renameTag($oldName, $newName); $io->success('Tag properly renamed.'); return ExitCodes::EXIT_SUCCESS; - } catch (EntityDoesNotExistException $e) { - $io->error(sprintf('A tag with name "%s" was not found', $oldName)); - return ExitCodes::EXIT_FAILURE; - } catch (TagConflictException $e) { - $io->error( - sprintf('A tag with name "%s" cannot be renamed to "%s" because it already exists', $oldName, $newName) - ); + } catch (TagNotFoundException | TagConflictException $e) { + $io->error($e->getMessage()); return ExitCodes::EXIT_FAILURE; } } diff --git a/module/CLI/src/Command/Util/AbstractLockedCommand.php b/module/CLI/src/Command/Util/AbstractLockedCommand.php index 0e206cbe..59ea74fa 100644 --- a/module/CLI/src/Command/Util/AbstractLockedCommand.php +++ b/module/CLI/src/Command/Util/AbstractLockedCommand.php @@ -8,16 +8,16 @@ use Shlinkio\Shlink\CLI\Util\ExitCodes; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Lock\Factory as Locker; +use Symfony\Component\Lock\LockFactory; use function sprintf; abstract class AbstractLockedCommand extends Command { - /** @var Locker */ + /** @var LockFactory */ private $locker; - public function __construct(Locker $locker) + public function __construct(LockFactory $locker) { parent::__construct(); $this->locker = $locker; diff --git a/module/CLI/src/Command/Util/AbstractWithDateRangeCommand.php b/module/CLI/src/Command/Util/AbstractWithDateRangeCommand.php new file mode 100644 index 00000000..c6b10be6 --- /dev/null +++ b/module/CLI/src/Command/Util/AbstractWithDateRangeCommand.php @@ -0,0 +1,54 @@ +doConfigure(); + $this + ->addOption('startDate', 's', InputOption::VALUE_REQUIRED, $this->getStartDateDesc()) + ->addOption('endDate', 'e', InputOption::VALUE_REQUIRED, $this->getEndDateDesc()); + } + + protected function getDateOption(InputInterface $input, OutputInterface $output, string $key): ?Chronos + { + $value = $input->getOption($key); + if (empty($value)) { + return null; + } + + try { + return Chronos::parse($value); + } catch (Throwable $e) { + $output->writeln(sprintf( + '> Ignored provided "%s" since its value "%s" is not a valid date. <', + $key, + $value + )); + + if ($output->isVeryVerbose()) { + $this->getApplication()->renderThrowable($e, $output); + } + + return null; + } + } + + abstract protected function doConfigure(): void; + + abstract protected function getStartDateDesc(): string; + abstract protected function getEndDateDesc(): string; +} diff --git a/module/CLI/src/Command/Visit/LocateVisitsCommand.php b/module/CLI/src/Command/Visit/LocateVisitsCommand.php index 21012480..710c4a3a 100644 --- a/module/CLI/src/Command/Visit/LocateVisitsCommand.php +++ b/module/CLI/src/Command/Visit/LocateVisitsCommand.php @@ -22,7 +22,7 @@ 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 Symfony\Component\Lock\Factory as Locker; +use Symfony\Component\Lock\LockFactory; use Throwable; use function sprintf; @@ -47,7 +47,7 @@ class LocateVisitsCommand extends AbstractLockedCommand public function __construct( VisitServiceInterface $visitService, IpLocationResolverInterface $ipLocationResolver, - Locker $locker, + LockFactory $locker, GeolocationDbUpdaterInterface $dbUpdater ) { parent::__construct($locker); @@ -87,7 +87,7 @@ class LocateVisitsCommand extends AbstractLockedCommand } catch (Throwable $e) { $this->io->error($e->getMessage()); if ($e instanceof Exception && $this->io->isVerbose()) { - $this->getApplication()->renderException($e, $this->io); + $this->getApplication()->renderThrowable($e, $this->io); } return ExitCodes::EXIT_FAILURE; @@ -116,7 +116,7 @@ class LocateVisitsCommand extends AbstractLockedCommand } catch (WrongIpException $e) { $this->io->writeln(' [An error occurred while locating IP. Skipped]'); if ($this->io->isVerbose()) { - $this->getApplication()->renderException($e, $this->io); + $this->getApplication()->renderThrowable($e, $this->io); } throw IpCannotBeLocatedException::forError($e); diff --git a/module/CLI/src/Command/Visit/UpdateDbCommand.php b/module/CLI/src/Command/Visit/UpdateDbCommand.php index c138372b..367423fd 100644 --- a/module/CLI/src/Command/Visit/UpdateDbCommand.php +++ b/module/CLI/src/Command/Visit/UpdateDbCommand.php @@ -84,7 +84,7 @@ class UpdateDbCommand extends Command $io->error($baseErrorMsg); if ($io->isVerbose()) { - $this->getApplication()->renderException($e, $io); + $this->getApplication()->renderThrowable($e, $io); } return ExitCodes::EXIT_FAILURE; } diff --git a/module/CLI/src/Exception/GeolocationDbUpdateFailedException.php b/module/CLI/src/Exception/GeolocationDbUpdateFailedException.php index fcb680d5..38bb4c5f 100644 --- a/module/CLI/src/Exception/GeolocationDbUpdateFailedException.php +++ b/module/CLI/src/Exception/GeolocationDbUpdateFailedException.php @@ -12,20 +12,16 @@ class GeolocationDbUpdateFailedException extends RuntimeException implements Exc /** @var bool */ private $olderDbExists; - public function __construct(bool $olderDbExists, string $message = '', int $code = 0, ?Throwable $previous = null) - { - $this->olderDbExists = $olderDbExists; - parent::__construct($message, $code, $previous); - } - public static function create(bool $olderDbExists, ?Throwable $prev = null): self { - return new self( - $olderDbExists, + $e = new self( 'An error occurred while updating geolocation database, and an older version could not be found', 0, $prev ); + $e->olderDbExists = $olderDbExists; + + return $e; } public function olderDbExists(): bool diff --git a/module/CLI/src/Util/GeolocationDbUpdater.php b/module/CLI/src/Util/GeolocationDbUpdater.php index ebff82aa..25b49c37 100644 --- a/module/CLI/src/Util/GeolocationDbUpdater.php +++ b/module/CLI/src/Util/GeolocationDbUpdater.php @@ -9,8 +9,7 @@ use GeoIp2\Database\Reader; use Shlinkio\Shlink\CLI\Exception\GeolocationDbUpdateFailedException; use Shlinkio\Shlink\IpGeolocation\Exception\RuntimeException; use Shlinkio\Shlink\IpGeolocation\GeoLite2\DbUpdaterInterface; -use Symfony\Component\Lock\Factory as Locker; -use Throwable; +use Symfony\Component\Lock\LockFactory; class GeolocationDbUpdater implements GeolocationDbUpdaterInterface { @@ -20,10 +19,10 @@ class GeolocationDbUpdater implements GeolocationDbUpdaterInterface private $dbUpdater; /** @var Reader */ private $geoLiteDbReader; - /** @var Locker */ + /** @var LockFactory */ private $locker; - public function __construct(DbUpdaterInterface $dbUpdater, Reader $geoLiteDbReader, Locker $locker) + public function __construct(DbUpdaterInterface $dbUpdater, Reader $geoLiteDbReader, LockFactory $locker) { $this->dbUpdater = $dbUpdater; $this->geoLiteDbReader = $geoLiteDbReader; @@ -40,8 +39,6 @@ class GeolocationDbUpdater implements GeolocationDbUpdaterInterface try { $this->downloadIfNeeded($mustBeUpdated, $handleProgress); - } catch (Throwable $e) { - throw $e; } finally { $lock->release(); } diff --git a/module/CLI/test/Command/Api/DisableKeyCommandTest.php b/module/CLI/test/Command/Api/DisableKeyCommandTest.php index ca17aa7a..37629091 100644 --- a/module/CLI/test/Command/Api/DisableKeyCommandTest.php +++ b/module/CLI/test/Command/Api/DisableKeyCommandTest.php @@ -29,7 +29,7 @@ class DisableKeyCommandTest extends TestCase } /** @test */ - public function providedApiKeyIsDisabled() + public function providedApiKeyIsDisabled(): void { $apiKey = 'abcd1234'; $this->apiKeyService->disable($apiKey)->shouldBeCalledOnce(); @@ -43,17 +43,18 @@ class DisableKeyCommandTest extends TestCase } /** @test */ - public function errorIsReturnedIfServiceThrowsException() + public function errorIsReturnedIfServiceThrowsException(): void { $apiKey = 'abcd1234'; - $disable = $this->apiKeyService->disable($apiKey)->willThrow(InvalidArgumentException::class); + $expectedMessage = 'API key "abcd1234" does not exist.'; + $disable = $this->apiKeyService->disable($apiKey)->willThrow(new InvalidArgumentException($expectedMessage)); $this->commandTester->execute([ 'apiKey' => $apiKey, ]); $output = $this->commandTester->getDisplay(); - $this->assertStringContainsString('API key "abcd1234" does not exist.', $output); + $this->assertStringContainsString($expectedMessage, $output); $disable->shouldHaveBeenCalledOnce(); } } diff --git a/module/CLI/test/Command/Db/CreateDatabaseCommandTest.php b/module/CLI/test/Command/Db/CreateDatabaseCommandTest.php index 89322544..7945ea05 100644 --- a/module/CLI/test/Command/Db/CreateDatabaseCommandTest.php +++ b/module/CLI/test/Command/Db/CreateDatabaseCommandTest.php @@ -15,7 +15,7 @@ use Symfony\Component\Console\Application; use Symfony\Component\Console\Helper\ProcessHelper; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Tester\CommandTester; -use Symfony\Component\Lock\Factory as Locker; +use Symfony\Component\Lock\LockFactory; use Symfony\Component\Lock\LockInterface; use Symfony\Component\Process\PhpExecutableFinder; @@ -36,7 +36,7 @@ class CreateDatabaseCommandTest extends TestCase public function setUp(): void { - $locker = $this->prophesize(Locker::class); + $locker = $this->prophesize(LockFactory::class); $lock = $this->prophesize(LockInterface::class); $lock->acquire(Argument::any())->willReturn(true); $lock->release()->will(function () { diff --git a/module/CLI/test/Command/Db/MigrateDatabaseCommandTest.php b/module/CLI/test/Command/Db/MigrateDatabaseCommandTest.php index 1e7690ae..be36a980 100644 --- a/module/CLI/test/Command/Db/MigrateDatabaseCommandTest.php +++ b/module/CLI/test/Command/Db/MigrateDatabaseCommandTest.php @@ -12,7 +12,7 @@ use Symfony\Component\Console\Application; use Symfony\Component\Console\Helper\ProcessHelper; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Tester\CommandTester; -use Symfony\Component\Lock\Factory as Locker; +use Symfony\Component\Lock\LockFactory; use Symfony\Component\Lock\LockInterface; use Symfony\Component\Process\PhpExecutableFinder; @@ -25,7 +25,7 @@ class MigrateDatabaseCommandTest extends TestCase public function setUp(): void { - $locker = $this->prophesize(Locker::class); + $locker = $this->prophesize(LockFactory::class); $lock = $this->prophesize(LockInterface::class); $lock->acquire(Argument::any())->willReturn(true); $lock->release()->will(function () { diff --git a/module/CLI/test/Command/ShortUrl/DeleteShortUrlCommandTest.php b/module/CLI/test/Command/ShortUrl/DeleteShortUrlCommandTest.php index f0fad2cc..85521835 100644 --- a/module/CLI/test/Command/ShortUrl/DeleteShortUrlCommandTest.php +++ b/module/CLI/test/Command/ShortUrl/DeleteShortUrlCommandTest.php @@ -58,13 +58,13 @@ class DeleteShortUrlCommandTest extends TestCase { $shortCode = 'abc123'; $deleteByShortCode = $this->service->deleteByShortCode($shortCode, false)->willThrow( - Exception\InvalidShortCodeException::class + Exception\ShortUrlNotFoundException::fromNotFoundShortCode($shortCode) ); $this->commandTester->execute(['shortCode' => $shortCode]); $output = $this->commandTester->getDisplay(); - $this->assertStringContainsString(sprintf('Provided short code "%s" could not be found.', $shortCode), $output); + $this->assertStringContainsString(sprintf('No URL found with short code "%s"', $shortCode), $output); $deleteByShortCode->shouldHaveBeenCalledOnce(); } @@ -79,11 +79,11 @@ class DeleteShortUrlCommandTest extends TestCase ): void { $shortCode = 'abc123'; $deleteByShortCode = $this->service->deleteByShortCode($shortCode, Argument::type('bool'))->will( - function (array $args) { + function (array $args) use ($shortCode) { $ignoreThreshold = array_pop($args); if (!$ignoreThreshold) { - throw new Exception\DeleteShortUrlException(10); + throw Exception\DeleteShortUrlException::fromVisitsThreshold(10, $shortCode); } } ); @@ -93,7 +93,7 @@ class DeleteShortUrlCommandTest extends TestCase $output = $this->commandTester->getDisplay(); $this->assertStringContainsString(sprintf( - 'It was not possible to delete the short URL with short code "%s" because it has more than 10 visits.', + 'Impossible to delete short URL with short code "%s" since it has more than "10" visits.', $shortCode ), $output); $this->assertStringContainsString($expectedMessage, $output); @@ -112,7 +112,7 @@ class DeleteShortUrlCommandTest extends TestCase { $shortCode = 'abc123'; $deleteByShortCode = $this->service->deleteByShortCode($shortCode, false)->willThrow( - new Exception\DeleteShortUrlException(10) + Exception\DeleteShortUrlException::fromVisitsThreshold(10, $shortCode) ); $this->commandTester->setInputs(['no']); @@ -120,7 +120,7 @@ class DeleteShortUrlCommandTest extends TestCase $output = $this->commandTester->getDisplay(); $this->assertStringContainsString(sprintf( - 'It was not possible to delete the short URL with short code "%s" because it has more than 10 visits.', + 'Impossible to delete short URL with short code "%s" since it has more than "10" visits.', $shortCode ), $output); $this->assertStringContainsString('Short URL was not deleted.', $output); diff --git a/module/CLI/test/Command/ShortUrl/GenerateShortUrlCommandTest.php b/module/CLI/test/Command/ShortUrl/GenerateShortUrlCommandTest.php index d83bd042..abae0fe6 100644 --- a/module/CLI/test/Command/ShortUrl/GenerateShortUrlCommandTest.php +++ b/module/CLI/test/Command/ShortUrl/GenerateShortUrlCommandTest.php @@ -59,21 +59,22 @@ class GenerateShortUrlCommandTest extends TestCase /** @test */ public function exceptionWhileParsingLongUrlOutputsError(): void { - $this->urlShortener->urlToShortCode(Argument::cetera())->willThrow(new InvalidUrlException()) + $url = 'http://domain.com/invalid'; + $this->urlShortener->urlToShortCode(Argument::cetera())->willThrow(InvalidUrlException::fromUrl($url)) ->shouldBeCalledOnce(); - $this->commandTester->execute(['longUrl' => 'http://domain.com/invalid']); + $this->commandTester->execute(['longUrl' => $url]); $output = $this->commandTester->getDisplay(); $this->assertEquals(ExitCodes::EXIT_FAILURE, $this->commandTester->getStatusCode()); - $this->assertStringContainsString('Provided URL "http://domain.com/invalid" is invalid.', $output); + $this->assertStringContainsString('Provided URL http://domain.com/invalid is invalid.', $output); } /** @test */ public function providingNonUniqueSlugOutputsError(): void { $urlToShortCode = $this->urlShortener->urlToShortCode(Argument::cetera())->willThrow( - NonUniqueSlugException::class + NonUniqueSlugException::fromSlug('my-slug') ); $this->commandTester->execute(['longUrl' => 'http://domain.com/invalid', '--customSlug' => 'my-slug']); diff --git a/module/CLI/test/Command/ShortUrl/GetVisitsCommandTest.php b/module/CLI/test/Command/ShortUrl/GetVisitsCommandTest.php index a61dd7d4..e2ea29d1 100644 --- a/module/CLI/test/Command/ShortUrl/GetVisitsCommandTest.php +++ b/module/CLI/test/Command/ShortUrl/GetVisitsCommandTest.php @@ -22,6 +22,8 @@ use Symfony\Component\Console\Tester\CommandTester; use Zend\Paginator\Adapter\ArrayAdapter; use Zend\Paginator\Paginator; +use function sprintf; + class GetVisitsCommandTest extends TestCase { /** @var CommandTester */ @@ -39,7 +41,7 @@ class GetVisitsCommandTest extends TestCase } /** @test */ - public function noDateFlagsTriesToListWithoutDateRange() + public function noDateFlagsTriesToListWithoutDateRange(): void { $shortCode = 'abc123'; $this->visitsTracker->info($shortCode, new VisitsParams(new DateRange(null, null)))->willReturn( @@ -50,7 +52,7 @@ class GetVisitsCommandTest extends TestCase } /** @test */ - public function providingDateFlagsTheListGetsFiltered() + public function providingDateFlagsTheListGetsFiltered(): void { $shortCode = 'abc123'; $startDate = '2016-01-01'; @@ -69,6 +71,27 @@ class GetVisitsCommandTest extends TestCase ]); } + /** @test */ + public function providingInvalidDatesPrintsWarning(): void + { + $shortCode = 'abc123'; + $startDate = 'foo'; + $info = $this->visitsTracker->info($shortCode, new VisitsParams(new DateRange())) + ->willReturn(new Paginator(new ArrayAdapter([]))); + + $this->commandTester->execute([ + 'shortCode' => $shortCode, + '--startDate' => $startDate, + ]); + $output = $this->commandTester->getDisplay(); + + $info->shouldHaveBeenCalledOnce(); + $this->assertStringContainsString( + sprintf('Ignored provided "startDate" since its value "%s" is not a valid date', $startDate), + $output + ); + } + /** @test */ public function outputIsProperlyGenerated(): void { diff --git a/module/CLI/test/Command/ShortUrl/ListShortUrlsCommandTest.php b/module/CLI/test/Command/ShortUrl/ListShortUrlsCommandTest.php index 6ad96ed3..0bf3bfab 100644 --- a/module/CLI/test/Command/ShortUrl/ListShortUrlsCommandTest.php +++ b/module/CLI/test/Command/ShortUrl/ListShortUrlsCommandTest.php @@ -4,10 +4,12 @@ declare(strict_types=1); namespace ShlinkioTest\Shlink\CLI\Command\ShortUrl; +use Cake\Chronos\Chronos; use PHPUnit\Framework\TestCase; use Prophecy\Argument; use Prophecy\Prophecy\ObjectProphecy; use Shlinkio\Shlink\CLI\Command\ShortUrl\ListShortUrlsCommand; +use Shlinkio\Shlink\Common\Util\DateRange; use Shlinkio\Shlink\Core\Entity\ShortUrl; use Shlinkio\Shlink\Core\Service\ShortUrlServiceInterface; use Symfony\Component\Console\Application; @@ -15,6 +17,8 @@ use Symfony\Component\Console\Tester\CommandTester; use Zend\Paginator\Adapter\ArrayAdapter; use Zend\Paginator\Paginator; +use function explode; + class ListShortUrlsCommandTest extends TestCase { /** @var CommandTester */ @@ -32,17 +36,7 @@ class ListShortUrlsCommandTest extends TestCase } /** @test */ - public function noInputCallsListJustOnce() - { - $this->shortUrlService->listShortUrls(1, null, [], null)->willReturn(new Paginator(new ArrayAdapter())) - ->shouldBeCalledOnce(); - - $this->commandTester->setInputs(['n']); - $this->commandTester->execute([]); - } - - /** @test */ - public function loadingMorePagesCallsListMoreTimes() + public function loadingMorePagesCallsListMoreTimes(): void { // The paginator will return more than one page $data = []; @@ -64,7 +58,7 @@ class ListShortUrlsCommandTest extends TestCase } /** @test */ - public function havingMorePagesButAnsweringNoCallsListJustOnce() + public function havingMorePagesButAnsweringNoCallsListJustOnce(): void { // The paginator will return more than one page $data = []; @@ -72,8 +66,9 @@ class ListShortUrlsCommandTest extends TestCase $data[] = new ShortUrl('url_' . $i); } - $this->shortUrlService->listShortUrls(1, null, [], null)->willReturn(new Paginator(new ArrayAdapter($data))) - ->shouldBeCalledOnce(); + $this->shortUrlService->listShortUrls(1, null, [], null, new DateRange()) + ->willReturn(new Paginator(new ArrayAdapter($data))) + ->shouldBeCalledOnce(); $this->commandTester->setInputs(['n']); $this->commandTester->execute([]); @@ -89,25 +84,105 @@ class ListShortUrlsCommandTest extends TestCase } /** @test */ - public function passingPageWillMakeListStartOnThatPage() + public function passingPageWillMakeListStartOnThatPage(): void { $page = 5; - $this->shortUrlService->listShortUrls($page, null, [], null)->willReturn(new Paginator(new ArrayAdapter())) - ->shouldBeCalledOnce(); + $this->shortUrlService->listShortUrls($page, null, [], null, new DateRange()) + ->willReturn(new Paginator(new ArrayAdapter())) + ->shouldBeCalledOnce(); $this->commandTester->setInputs(['y']); $this->commandTester->execute(['--page' => $page]); } /** @test */ - public function ifTagsFlagIsProvidedTagsColumnIsIncluded() + public function ifTagsFlagIsProvidedTagsColumnIsIncluded(): void { - $this->shortUrlService->listShortUrls(1, null, [], null)->willReturn(new Paginator(new ArrayAdapter())) - ->shouldBeCalledOnce(); + $this->shortUrlService->listShortUrls(1, null, [], null, new DateRange()) + ->willReturn(new Paginator(new ArrayAdapter())) + ->shouldBeCalledOnce(); $this->commandTester->setInputs(['y']); $this->commandTester->execute(['--showTags' => true]); $output = $this->commandTester->getDisplay(); $this->assertStringContainsString('Tags', $output); } + + /** + * @test + * @dataProvider provideArgs + */ + public function serviceIsInvokedWithProvidedArgs( + array $commandArgs, + ?int $page, + ?string $searchTerm, + array $tags, + ?DateRange $dateRange + ): void { + $listShortUrls = $this->shortUrlService->listShortUrls($page, $searchTerm, $tags, null, $dateRange) + ->willReturn(new Paginator(new ArrayAdapter())); + + $this->commandTester->setInputs(['n']); + $this->commandTester->execute($commandArgs); + + $listShortUrls->shouldHaveBeenCalledOnce(); + } + + public function provideArgs(): iterable + { + yield [[], 1, null, [], new DateRange()]; + yield [['--page' => $page = 3], $page, null, [], new DateRange()]; + yield [['--searchTerm' => $searchTerm = 'search this'], 1, $searchTerm, [], new DateRange()]; + yield [ + ['--page' => $page = 3, '--searchTerm' => $searchTerm = 'search this', '--tags' => $tags = 'foo,bar'], + $page, + $searchTerm, + explode(',', $tags), + new DateRange(), + ]; + yield [ + ['--startDate' => $startDate = '2019-01-01'], + 1, + null, + [], + new DateRange(Chronos::parse($startDate)), + ]; + yield [ + ['--endDate' => $endDate = '2020-05-23'], + 1, + null, + [], + new DateRange(null, Chronos::parse($endDate)), + ]; + yield [ + ['--startDate' => $startDate = '2019-01-01', '--endDate' => $endDate = '2020-05-23'], + 1, + null, + [], + new DateRange(Chronos::parse($startDate), Chronos::parse($endDate)), + ]; + } + + /** + * @test + * @dataProvider provideOrderBy + */ + public function orderByIsProperlyComputed(array $commandArgs, $expectedOrderBy): void + { + $listShortUrls = $this->shortUrlService->listShortUrls(1, null, [], $expectedOrderBy, new DateRange()) + ->willReturn(new Paginator(new ArrayAdapter())); + + $this->commandTester->setInputs(['n']); + $this->commandTester->execute($commandArgs); + + $listShortUrls->shouldHaveBeenCalledOnce(); + } + + public function provideOrderBy(): iterable + { + yield [[], null]; + yield [['--orderBy' => 'foo'], 'foo']; + yield [['--orderBy' => 'foo,ASC'], ['foo' => 'ASC']]; + yield [['--orderBy' => 'bar,DESC'], ['bar' => 'DESC']]; + } } diff --git a/module/CLI/test/Command/ShortUrl/ResolveUrlCommandTest.php b/module/CLI/test/Command/ShortUrl/ResolveUrlCommandTest.php index 283b3a4f..11b549e5 100644 --- a/module/CLI/test/Command/ShortUrl/ResolveUrlCommandTest.php +++ b/module/CLI/test/Command/ShortUrl/ResolveUrlCommandTest.php @@ -8,12 +8,13 @@ use PHPUnit\Framework\TestCase; use Prophecy\Prophecy\ObjectProphecy; use Shlinkio\Shlink\CLI\Command\ShortUrl\ResolveUrlCommand; use Shlinkio\Shlink\Core\Entity\ShortUrl; -use Shlinkio\Shlink\Core\Exception\EntityDoesNotExistException; -use Shlinkio\Shlink\Core\Exception\InvalidShortCodeException; +use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException; use Shlinkio\Shlink\Core\Service\UrlShortener; use Symfony\Component\Console\Application; use Symfony\Component\Console\Tester\CommandTester; +use function sprintf; + use const PHP_EOL; class ResolveUrlCommandTest extends TestCase @@ -51,23 +52,12 @@ class ResolveUrlCommandTest extends TestCase public function incorrectShortCodeOutputsErrorMessage(): void { $shortCode = 'abc123'; - $this->urlShortener->shortCodeToUrl($shortCode, null)->willThrow(EntityDoesNotExistException::class) - ->shouldBeCalledOnce(); + $this->urlShortener->shortCodeToUrl($shortCode, null) + ->willThrow(ShortUrlNotFoundException::fromNotFoundShortCode($shortCode)) + ->shouldBeCalledOnce(); $this->commandTester->execute(['shortCode' => $shortCode]); $output = $this->commandTester->getDisplay(); - $this->assertStringContainsString('Provided short code "' . $shortCode . '" could not be found.', $output); - } - - /** @test */ - public function wrongShortCodeFormatOutputsErrorMessage(): void - { - $shortCode = 'abc123'; - $this->urlShortener->shortCodeToUrl($shortCode, null)->willThrow(new InvalidShortCodeException()) - ->shouldBeCalledOnce(); - - $this->commandTester->execute(['shortCode' => $shortCode]); - $output = $this->commandTester->getDisplay(); - $this->assertStringContainsString('Provided short code "' . $shortCode . '" has an invalid format.', $output); + $this->assertStringContainsString(sprintf('No URL found with short code "%s"', $shortCode), $output); } } diff --git a/module/CLI/test/Command/Tag/RenameTagCommandTest.php b/module/CLI/test/Command/Tag/RenameTagCommandTest.php index 228d854d..c626e0c0 100644 --- a/module/CLI/test/Command/Tag/RenameTagCommandTest.php +++ b/module/CLI/test/Command/Tag/RenameTagCommandTest.php @@ -8,7 +8,7 @@ use PHPUnit\Framework\TestCase; use Prophecy\Prophecy\ObjectProphecy; use Shlinkio\Shlink\CLI\Command\Tag\RenameTagCommand; use Shlinkio\Shlink\Core\Entity\Tag; -use Shlinkio\Shlink\Core\Exception\EntityDoesNotExistException; +use Shlinkio\Shlink\Core\Exception\TagNotFoundException; use Shlinkio\Shlink\Core\Service\Tag\TagServiceInterface; use Symfony\Component\Console\Application; use Symfony\Component\Console\Tester\CommandTester; @@ -34,11 +34,11 @@ class RenameTagCommandTest extends TestCase } /** @test */ - public function errorIsPrintedIfExceptionIsThrown() + public function errorIsPrintedIfExceptionIsThrown(): void { $oldName = 'foo'; $newName = 'bar'; - $renameTag = $this->tagService->renameTag($oldName, $newName)->willThrow(EntityDoesNotExistException::class); + $renameTag = $this->tagService->renameTag($oldName, $newName)->willThrow(TagNotFoundException::fromTag('foo')); $this->commandTester->execute([ 'oldName' => $oldName, @@ -46,12 +46,12 @@ class RenameTagCommandTest extends TestCase ]); $output = $this->commandTester->getDisplay(); - $this->assertStringContainsString('A tag with name "foo" was not found', $output); + $this->assertStringContainsString('Tag with name "foo" could not be found', $output); $renameTag->shouldHaveBeenCalled(); } /** @test */ - public function successIsPrintedIfNoErrorOccurs() + public function successIsPrintedIfNoErrorOccurs(): void { $oldName = 'foo'; $newName = 'bar'; diff --git a/module/CLI/test/Command/Visit/LocateVisitsCommandTest.php b/module/CLI/test/Command/Visit/LocateVisitsCommandTest.php index bb3be84c..e01bf85f 100644 --- a/module/CLI/test/Command/Visit/LocateVisitsCommandTest.php +++ b/module/CLI/test/Command/Visit/LocateVisitsCommandTest.php @@ -48,7 +48,7 @@ class LocateVisitsCommandTest extends TestCase $this->ipResolver = $this->prophesize(IpLocationResolverInterface::class); $this->dbUpdater = $this->prophesize(GeolocationDbUpdaterInterface::class); - $this->locker = $this->prophesize(Lock\Factory::class); + $this->locker = $this->prophesize(Lock\LockFactory::class); $this->lock = $this->prophesize(Lock\LockInterface::class); $this->lock->acquire(false)->willReturn(true); $this->lock->release()->will(function () { diff --git a/module/CLI/test/Exception/GeolocationDbUpdateFailedExceptionTest.php b/module/CLI/test/Exception/GeolocationDbUpdateFailedExceptionTest.php index 51c87cb3..70a8cc6f 100644 --- a/module/CLI/test/Exception/GeolocationDbUpdateFailedExceptionTest.php +++ b/module/CLI/test/Exception/GeolocationDbUpdateFailedExceptionTest.php @@ -12,47 +12,6 @@ use Throwable; class GeolocationDbUpdateFailedExceptionTest extends TestCase { - /** - * @test - * @dataProvider provideOlderDbExists - */ - public function constructCreatesExceptionWithDefaultArgs(bool $olderDbExists): void - { - $e = new GeolocationDbUpdateFailedException($olderDbExists); - - $this->assertEquals($olderDbExists, $e->olderDbExists()); - $this->assertEquals('', $e->getMessage()); - $this->assertEquals(0, $e->getCode()); - $this->assertNull($e->getPrevious()); - } - - public function provideOlderDbExists(): iterable - { - yield 'with older DB' => [true]; - yield 'without older DB' => [false]; - } - - /** - * @test - * @dataProvider provideConstructorArgs - */ - public function constructCreatesException(bool $olderDbExists, string $message, int $code, ?Throwable $prev): void - { - $e = new GeolocationDbUpdateFailedException($olderDbExists, $message, $code, $prev); - - $this->assertEquals($olderDbExists, $e->olderDbExists()); - $this->assertEquals($message, $e->getMessage()); - $this->assertEquals($code, $e->getCode()); - $this->assertEquals($prev, $e->getPrevious()); - } - - public function provideConstructorArgs(): iterable - { - yield [true, 'This is a nice error message', 99, new Exception('prev')]; - yield [false, 'Another message', 0, new RuntimeException('prev')]; - yield [true, 'An yet another message', -50, null]; - } - /** * @test * @dataProvider provideCreateArgs diff --git a/module/CLI/test/Util/GeolocationDbUpdaterTest.php b/module/CLI/test/Util/GeolocationDbUpdaterTest.php index 56819924..f2b0f98c 100644 --- a/module/CLI/test/Util/GeolocationDbUpdaterTest.php +++ b/module/CLI/test/Util/GeolocationDbUpdaterTest.php @@ -38,7 +38,7 @@ class GeolocationDbUpdaterTest extends TestCase $this->dbUpdater = $this->prophesize(DbUpdaterInterface::class); $this->geoLiteDbReader = $this->prophesize(Reader::class); - $this->locker = $this->prophesize(Lock\Factory::class); + $this->locker = $this->prophesize(Lock\LockFactory::class); $this->lock = $this->prophesize(Lock\LockInterface::class); $this->lock->acquire(true)->willReturn(true); $this->lock->release()->will(function () { diff --git a/module/Core/config/dependencies.config.php b/module/Core/config/dependencies.config.php index 426d0969..0ebdae7d 100644 --- a/module/Core/config/dependencies.config.php +++ b/module/Core/config/dependencies.config.php @@ -6,8 +6,8 @@ namespace Shlinkio\Shlink\Core; use Doctrine\Common\Cache\Cache; use Psr\EventDispatcher\EventDispatcherInterface; +use Shlinkio\Shlink\Core\ErrorHandler; use Shlinkio\Shlink\Core\Options\NotFoundRedirectOptions; -use Shlinkio\Shlink\Core\Response\NotFoundHandler; use Shlinkio\Shlink\PreviewGenerator\Service\PreviewGenerator; use Zend\Expressive\Router\RouterInterface; use Zend\Expressive\Template\TemplateRendererInterface; @@ -17,7 +17,8 @@ return [ 'dependencies' => [ 'factories' => [ - NotFoundHandler::class => ConfigAbstractFactory::class, + ErrorHandler\NotFoundRedirectHandler::class => ConfigAbstractFactory::class, + ErrorHandler\NotFoundTemplateHandler::class => ConfigAbstractFactory::class, Options\AppOptions::class => ConfigAbstractFactory::class, Options\DeleteShortUrlsOptions::class => ConfigAbstractFactory::class, @@ -43,11 +44,8 @@ return [ ], ConfigAbstractFactory::class => [ - NotFoundHandler::class => [ - TemplateRendererInterface::class, - NotFoundRedirectOptions::class, - 'config.router.base_path', - ], + ErrorHandler\NotFoundRedirectHandler::class => [NotFoundRedirectOptions::class, 'config.router.base_path'], + ErrorHandler\NotFoundTemplateHandler::class => [TemplateRendererInterface::class], Options\AppOptions::class => ['config.app_options'], Options\DeleteShortUrlsOptions::class => ['config.delete_short_urls'], diff --git a/module/Core/config/event_dispatcher.config.php b/module/Core/config/event_dispatcher.config.php index b5d86b09..aead1447 100644 --- a/module/Core/config/event_dispatcher.config.php +++ b/module/Core/config/event_dispatcher.config.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Shlinkio\Shlink\Core; +use Psr\EventDispatcher\EventDispatcherInterface; use Shlinkio\Shlink\CLI\Util\GeolocationDbUpdater; use Shlinkio\Shlink\IpGeolocation\Resolver\IpLocationResolverInterface; use Zend\ServiceManager\AbstractFactory\ConfigAbstractFactory; @@ -11,7 +12,11 @@ use Zend\ServiceManager\AbstractFactory\ConfigAbstractFactory; return [ 'events' => [ - 'regular' => [], + 'regular' => [ + EventDispatcher\VisitLocated::class => [ + EventDispatcher\NotifyVisitToWebHooks::class, + ], + ], 'async' => [ EventDispatcher\ShortUrlVisited::class => [ EventDispatcher\LocateShortUrlVisit::class, @@ -22,6 +27,7 @@ return [ 'dependencies' => [ 'factories' => [ EventDispatcher\LocateShortUrlVisit::class => ConfigAbstractFactory::class, + EventDispatcher\NotifyVisitToWebHooks::class => ConfigAbstractFactory::class, ], ], @@ -31,6 +37,15 @@ return [ 'em', 'Logger_Shlink', GeolocationDbUpdater::class, + EventDispatcherInterface::class, + ], + EventDispatcher\NotifyVisitToWebHooks::class => [ + 'httpClient', + 'em', + 'Logger_Shlink', + 'config.url_shortener.visits_webhooks', + 'config.url_shortener.domain', + Options\AppOptions::class, ], ], diff --git a/module/Core/src/Action/AbstractTrackingAction.php b/module/Core/src/Action/AbstractTrackingAction.php index 9bacaf39..ff8d91f2 100644 --- a/module/Core/src/Action/AbstractTrackingAction.php +++ b/module/Core/src/Action/AbstractTrackingAction.php @@ -11,8 +11,7 @@ use Psr\Http\Server\RequestHandlerInterface; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; use Shlinkio\Shlink\Core\Entity\ShortUrl; -use Shlinkio\Shlink\Core\Exception\EntityDoesNotExistException; -use Shlinkio\Shlink\Core\Exception\InvalidShortCodeException; +use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException; use Shlinkio\Shlink\Core\Model\Visitor; use Shlinkio\Shlink\Core\Options\AppOptions; use Shlinkio\Shlink\Core\Service\UrlShortenerInterface; @@ -72,7 +71,7 @@ abstract class AbstractTrackingAction implements MiddlewareInterface } return $this->createSuccessResp($this->buildUrlToRedirectTo($url, $query, $disableTrackParam)); - } catch (InvalidShortCodeException | EntityDoesNotExistException $e) { + } catch (ShortUrlNotFoundException $e) { $this->logger->warning('An error occurred while tracking short code. {e}', ['e' => $e]); return $this->createErrorResp($request, $handler); } diff --git a/module/Core/src/Action/PreviewAction.php b/module/Core/src/Action/PreviewAction.php index 4ac2a50c..d243f12c 100644 --- a/module/Core/src/Action/PreviewAction.php +++ b/module/Core/src/Action/PreviewAction.php @@ -11,8 +11,7 @@ use Psr\Http\Server\RequestHandlerInterface; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; use Shlinkio\Shlink\Common\Response\ResponseUtilsTrait; -use Shlinkio\Shlink\Core\Exception\EntityDoesNotExistException; -use Shlinkio\Shlink\Core\Exception\InvalidShortCodeException; +use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException; use Shlinkio\Shlink\Core\Service\UrlShortenerInterface; use Shlinkio\Shlink\PreviewGenerator\Exception\PreviewGenerationException; use Shlinkio\Shlink\PreviewGenerator\Service\PreviewGeneratorInterface; @@ -56,7 +55,7 @@ class PreviewAction implements MiddlewareInterface $url = $this->urlShortener->shortCodeToUrl($shortCode); $imagePath = $this->previewGenerator->generatePreview($url->getLongUrl()); return $this->generateImageResponse($imagePath); - } catch (InvalidShortCodeException | EntityDoesNotExistException | PreviewGenerationException $e) { + } catch (ShortUrlNotFoundException | PreviewGenerationException $e) { $this->logger->warning('An error occurred while generating preview image. {e}', ['e' => $e]); return $handler->handle($request); } diff --git a/module/Core/src/Action/QrCodeAction.php b/module/Core/src/Action/QrCodeAction.php index a1fdae5b..3cdee70e 100644 --- a/module/Core/src/Action/QrCodeAction.php +++ b/module/Core/src/Action/QrCodeAction.php @@ -12,8 +12,7 @@ use Psr\Http\Server\RequestHandlerInterface; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; use Shlinkio\Shlink\Common\Response\QrCodeResponse; -use Shlinkio\Shlink\Core\Exception\EntityDoesNotExistException; -use Shlinkio\Shlink\Core\Exception\InvalidShortCodeException; +use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException; use Shlinkio\Shlink\Core\Service\UrlShortenerInterface; use Zend\Expressive\Router\Exception\RuntimeException; use Zend\Expressive\Router\RouterInterface; @@ -60,7 +59,7 @@ class QrCodeAction implements MiddlewareInterface try { $this->urlShortener->shortCodeToUrl($shortCode, $domain); - } catch (InvalidShortCodeException | EntityDoesNotExistException $e) { + } catch (ShortUrlNotFoundException $e) { $this->logger->warning('An error occurred while creating QR code. {e}', ['e' => $e]); return $handler->handle($request); } diff --git a/module/Core/src/Config/SimplifiedConfigParser.php b/module/Core/src/Config/SimplifiedConfigParser.php index 95c777e8..5ee912b0 100644 --- a/module/Core/src/Config/SimplifiedConfigParser.php +++ b/module/Core/src/Config/SimplifiedConfigParser.php @@ -32,6 +32,7 @@ class SimplifiedConfigParser 'base_path' => ['router', 'base_path'], 'web_worker_num' => ['zend-expressive-swoole', 'swoole-http-server', 'options', 'worker_num'], 'task_worker_num' => ['zend-expressive-swoole', 'swoole-http-server', 'options', 'task_worker_num'], + 'visits_webhooks' => ['url_shortener', 'visits_webhooks'], ]; private const SIMPLIFIED_CONFIG_SIDE_EFFECTS = [ 'delete_short_url_threshold' => [ diff --git a/module/Core/src/Entity/Visit.php b/module/Core/src/Entity/Visit.php index ee1b5394..b2ce3640 100644 --- a/module/Core/src/Entity/Visit.php +++ b/module/Core/src/Entity/Visit.php @@ -61,6 +61,11 @@ class Visit extends AbstractEntity implements JsonSerializable return ! empty($this->remoteAddr); } + public function getShortUrl(): ShortUrl + { + return $this->shortUrl; + } + public function getVisitLocation(): VisitLocationInterface { return $this->visitLocation ?? new UnknownVisitLocation(); diff --git a/module/Core/src/Response/NotFoundHandler.php b/module/Core/src/ErrorHandler/NotFoundRedirectHandler.php similarity index 50% rename from module/Core/src/Response/NotFoundHandler.php rename to module/Core/src/ErrorHandler/NotFoundRedirectHandler.php index 6bf245c1..f6a03395 100644 --- a/module/Core/src/Response/NotFoundHandler.php +++ b/module/Core/src/ErrorHandler/NotFoundRedirectHandler.php @@ -2,78 +2,40 @@ declare(strict_types=1); -namespace Shlinkio\Shlink\Core\Response; +namespace Shlinkio\Shlink\Core\ErrorHandler; -use Fig\Http\Message\StatusCodeInterface; -use InvalidArgumentException; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\UriInterface; +use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use Shlinkio\Shlink\Core\Action\RedirectAction; use Shlinkio\Shlink\Core\Options\NotFoundRedirectOptions; use Zend\Diactoros\Response; use Zend\Expressive\Router\RouteResult; -use Zend\Expressive\Template\TemplateRendererInterface; -use function array_shift; -use function explode; -use function Functional\contains; use function rtrim; -class NotFoundHandler implements RequestHandlerInterface +class NotFoundRedirectHandler implements MiddlewareInterface { - public const NOT_FOUND_TEMPLATE = 'ShlinkCore::error/404'; - public const INVALID_SHORT_CODE_TEMPLATE = 'ShlinkCore::invalid-short-code'; - - /** @var TemplateRendererInterface */ - private $renderer; /** @var NotFoundRedirectOptions */ private $redirectOptions; /** @var string */ private $shlinkBasePath; - public function __construct( - TemplateRendererInterface $renderer, - NotFoundRedirectOptions $redirectOptions, - string $shlinkBasePath - ) { - $this->renderer = $renderer; + public function __construct(NotFoundRedirectOptions $redirectOptions, string $shlinkBasePath) + { $this->redirectOptions = $redirectOptions; $this->shlinkBasePath = $shlinkBasePath; } - /** - * Dispatch the next available middleware and return the response. - * - * @param ServerRequestInterface $request - * - * @return ResponseInterface - * @throws InvalidArgumentException - */ - public function handle(ServerRequestInterface $request): ResponseInterface + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { /** @var RouteResult $routeResult */ $routeResult = $request->getAttribute(RouteResult::class, RouteResult::fromRouteFailure(null)); $redirectResponse = $this->createRedirectResponse($routeResult, $request->getUri()); - if ($redirectResponse !== null) { - return $redirectResponse; - } - $accepts = explode(',', $request->getHeaderLine('Accept')); - $accept = array_shift($accepts); - $status = StatusCodeInterface::STATUS_NOT_FOUND; - - // If the first accepted type is json, return a json response - if (contains(['application/json', 'text/json', 'application/x-json'], $accept)) { - return new Response\JsonResponse([ - 'error' => 'NOT_FOUND', - 'message' => 'Not found', - ], $status); - } - - $template = $routeResult->isFailure() ? self::NOT_FOUND_TEMPLATE : self::INVALID_SHORT_CODE_TEMPLATE; - return new Response\HtmlResponse($this->renderer->render($template), $status); + return $redirectResponse ?? $handler->handle($request); } private function createRedirectResponse(RouteResult $routeResult, UriInterface $uri): ?ResponseInterface diff --git a/module/Core/src/ErrorHandler/NotFoundTemplateHandler.php b/module/Core/src/ErrorHandler/NotFoundTemplateHandler.php new file mode 100644 index 00000000..7b84043d --- /dev/null +++ b/module/Core/src/ErrorHandler/NotFoundTemplateHandler.php @@ -0,0 +1,46 @@ +renderer = $renderer; + } + + /** + * Dispatch the next available middleware and return the response. + * + * @param ServerRequestInterface $request + * + * @return ResponseInterface + * @throws InvalidArgumentException + */ + public function handle(ServerRequestInterface $request): ResponseInterface + { + /** @var RouteResult $routeResult */ + $routeResult = $request->getAttribute(RouteResult::class, RouteResult::fromRouteFailure(null)); + $status = StatusCodeInterface::STATUS_NOT_FOUND; + + $template = $routeResult->isFailure() ? self::NOT_FOUND_TEMPLATE : self::INVALID_SHORT_CODE_TEMPLATE; + return new Response\HtmlResponse($this->renderer->render($template), $status); + } +} diff --git a/module/Core/src/EventDispatcher/LocateShortUrlVisit.php b/module/Core/src/EventDispatcher/LocateShortUrlVisit.php index 65026af0..4d767272 100644 --- a/module/Core/src/EventDispatcher/LocateShortUrlVisit.php +++ b/module/Core/src/EventDispatcher/LocateShortUrlVisit.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace Shlinkio\Shlink\Core\EventDispatcher; use Doctrine\ORM\EntityManagerInterface; +use Psr\EventDispatcher\EventDispatcherInterface; use Psr\Log\LoggerInterface; use Shlinkio\Shlink\CLI\Exception\GeolocationDbUpdateFailedException; use Shlinkio\Shlink\CLI\Util\GeolocationDbUpdaterInterface; @@ -26,17 +27,21 @@ class LocateShortUrlVisit private $logger; /** @var GeolocationDbUpdaterInterface */ private $dbUpdater; + /** @var EventDispatcherInterface */ + private $eventDispatcher; public function __construct( IpLocationResolverInterface $ipLocationResolver, EntityManagerInterface $em, LoggerInterface $logger, - GeolocationDbUpdaterInterface $dbUpdater + GeolocationDbUpdaterInterface $dbUpdater, + EventDispatcherInterface $eventDispatcher ) { $this->ipLocationResolver = $ipLocationResolver; $this->em = $em; $this->logger = $logger; $this->dbUpdater = $dbUpdater; + $this->eventDispatcher = $eventDispatcher; } public function __invoke(ShortUrlVisited $shortUrlVisited): void @@ -46,10 +51,21 @@ class LocateShortUrlVisit /** @var Visit|null $visit */ $visit = $this->em->find(Visit::class, $visitId); if ($visit === null) { - $this->logger->warning(sprintf('Tried to locate visit with id "%s", but it does not exist.', $visitId)); + $this->logger->warning('Tried to locate visit with id "{visitId}", but it does not exist.', [ + 'visitId' => $visitId, + ]); return; } + if ($this->downloadOrUpdateGeoLiteDb($visitId)) { + $this->locateVisit($visitId, $visit); + } + + $this->eventDispatcher->dispatch(new VisitLocated($visitId)); + } + + private function downloadOrUpdateGeoLiteDb(string $visitId): bool + { try { $this->dbUpdater->checkDbUpdate(function (bool $olderDbExists) { $this->logger->notice(sprintf('%s GeoLite2 database...', $olderDbExists ? 'Updating' : 'Downloading')); @@ -57,31 +73,32 @@ class LocateShortUrlVisit } catch (GeolocationDbUpdateFailedException $e) { if (! $e->olderDbExists()) { $this->logger->error( - sprintf( - 'GeoLite2 database download failed. It is not possible to locate visit with id %s. {e}', - $visitId - ), - ['e' => $e] + 'GeoLite2 database download failed. It is not possible to locate visit with id {visitId}. {e}', + ['e' => $e, 'visitId' => $visitId] ); - return; + return false; } $this->logger->warning('GeoLite2 database update failed. Proceeding with old version. {e}', ['e' => $e]); } + return true; + } + + private function locateVisit(string $visitId, Visit $visit): void + { try { $location = $visit->isLocatable() ? $this->ipLocationResolver->resolveIpLocation($visit->getRemoteAddr()) : Location::emptyInstance(); + + $visit->locate(new VisitLocation($location)); + $this->em->flush(); } catch (WrongIpException $e) { $this->logger->warning( - sprintf('Tried to locate visit with id "%s", but its address seems to be wrong. {e}', $visitId), - ['e' => $e] + 'Tried to locate visit with id "{visitId}", but its address seems to be wrong. {e}', + ['e' => $e, 'visitId' => $visitId] ); - return; } - - $visit->locate(new VisitLocation($location)); - $this->em->flush($visit); } } diff --git a/module/Core/src/EventDispatcher/NotifyVisitToWebHooks.php b/module/Core/src/EventDispatcher/NotifyVisitToWebHooks.php new file mode 100644 index 00000000..d99defb5 --- /dev/null +++ b/module/Core/src/EventDispatcher/NotifyVisitToWebHooks.php @@ -0,0 +1,113 @@ +httpClient = $httpClient; + $this->em = $em; + $this->logger = $logger; + $this->webhooks = $webhooks; + $this->transformer = new ShortUrlDataTransformer($domainConfig); + $this->appOptions = $appOptions; + } + + public function __invoke(VisitLocated $shortUrlLocated): void + { + if (empty($this->webhooks)) { + return; + } + + $visitId = $shortUrlLocated->visitId(); + + /** @var Visit|null $visit */ + $visit = $this->em->find(Visit::class, $visitId); + if ($visit === null) { + $this->logger->warning('Tried to notify webhooks for visit with id "{visitId}", but it does not exist.', [ + 'visitId' => $visitId, + ]); + return; + } + + $requestOptions = $this->buildRequestOptions($visit); + $requestPromises = $this->performRequests($requestOptions, $visitId); + + // Wait for all the promises to finish, ignoring rejections, as in those cases we only want to log the error. + settle($requestPromises)->wait(); + } + + private function buildRequestOptions(Visit $visit): array + { + return [ + RequestOptions::TIMEOUT => 10, + RequestOptions::HEADERS => [ + 'User-Agent' => (string) $this->appOptions, + ], + RequestOptions::JSON => [ + 'shortUrl' => $this->transformer->transform($visit->getShortUrl(), false), + 'visit' => $visit->jsonSerialize(), + ], + ]; + } + + /** + * @param Promise[] $requestOptions + */ + private function performRequests(array $requestOptions, string $visitId): array + { + return map($this->webhooks, function (string $webhook) use ($requestOptions, $visitId) { + $promise = $this->httpClient->requestAsync(RequestMethodInterface::METHOD_POST, $webhook, $requestOptions); + return $promise->otherwise( + partial_left(Closure::fromCallable([$this, 'logWebhookFailure']), $webhook, $visitId) + ); + }); + } + + private function logWebhookFailure(string $webhook, string $visitId, Throwable $e): void + { + $this->logger->warning('Failed to notify visit with id "{visitId}" to webhook "{webhook}". {e}', [ + 'visitId' => $visitId, + 'webhook' => $webhook, + 'e' => $e, + ]); + } +} diff --git a/module/Core/src/EventDispatcher/VisitLocated.php b/module/Core/src/EventDispatcher/VisitLocated.php new file mode 100644 index 00000000..4873ffa7 --- /dev/null +++ b/module/Core/src/EventDispatcher/VisitLocated.php @@ -0,0 +1,28 @@ +visitId = $visitId; + } + + public function visitId(): string + { + return $this->visitId; + } + + public function jsonSerialize(): array + { + return ['visitId' => $this->visitId]; + } +} diff --git a/module/Core/src/Exception/DeleteShortUrlException.php b/module/Core/src/Exception/DeleteShortUrlException.php index c1fd6dd7..ddd77418 100644 --- a/module/Core/src/Exception/DeleteShortUrlException.php +++ b/module/Core/src/Exception/DeleteShortUrlException.php @@ -4,32 +4,41 @@ declare(strict_types=1); namespace Shlinkio\Shlink\Core\Exception; -use Throwable; +use Fig\Http\Message\StatusCodeInterface; +use Zend\ProblemDetails\Exception\CommonProblemDetailsExceptionTrait; +use Zend\ProblemDetails\Exception\ProblemDetailsExceptionInterface; use function sprintf; -class DeleteShortUrlException extends RuntimeException +class DeleteShortUrlException extends DomainException implements ProblemDetailsExceptionInterface { - /** @var int */ - private $visitsThreshold; + use CommonProblemDetailsExceptionTrait; - public function __construct(int $visitsThreshold, string $message = '', int $code = 0, ?Throwable $previous = null) - { - $this->visitsThreshold = $visitsThreshold; - parent::__construct($message, $code, $previous); - } + private const TITLE = 'Cannot delete short URL'; + private const TYPE = 'INVALID_SHORTCODE_DELETION'; // FIXME Should be INVALID_SHORT_URL_DELETION public static function fromVisitsThreshold(int $threshold, string $shortCode): self { - return new self($threshold, sprintf( + $e = new self(sprintf( 'Impossible to delete short URL with short code "%s" since it has more than "%s" visits.', $shortCode, $threshold )); + + $e->detail = $e->getMessage(); + $e->title = self::TITLE; + $e->type = self::TYPE; + $e->status = StatusCodeInterface::STATUS_UNPROCESSABLE_ENTITY; + $e->additional = [ + 'shortCode' => $shortCode, + 'threshold' => $threshold, + ]; + + return $e; } public function getVisitsThreshold(): int { - return $this->visitsThreshold; + return $this->additional['threshold']; } } diff --git a/module/Core/src/Exception/DomainException.php b/module/Core/src/Exception/DomainException.php new file mode 100644 index 00000000..63134952 --- /dev/null +++ b/module/Core/src/Exception/DomainException.php @@ -0,0 +1,11 @@ + $value) { - $result[] = sprintf('"%s" => "%s"', $key, $value); - } - - return implode(', ', $result); - } -} diff --git a/module/Core/src/Exception/InvalidShortCodeException.php b/module/Core/src/Exception/InvalidShortCodeException.php deleted file mode 100644 index 37ecfffb..00000000 --- a/module/Core/src/Exception/InvalidShortCodeException.php +++ /dev/null @@ -1,27 +0,0 @@ -getCode() : -1; - return new static( - sprintf('Provided short code "%s" does not match the char set "%s"', $shortCode, $charSet), - $code, - $previous - ); - } - - public static function fromNotFoundShortCode(string $shortCode): self - { - return new static(sprintf('Provided short code "%s" does not belong to a short URL', $shortCode)); - } -} diff --git a/module/Core/src/Exception/InvalidUrlException.php b/module/Core/src/Exception/InvalidUrlException.php index 5cd79af5..ffec94df 100644 --- a/module/Core/src/Exception/InvalidUrlException.php +++ b/module/Core/src/Exception/InvalidUrlException.php @@ -4,15 +4,31 @@ declare(strict_types=1); namespace Shlinkio\Shlink\Core\Exception; +use Fig\Http\Message\StatusCodeInterface; use Throwable; +use Zend\ProblemDetails\Exception\CommonProblemDetailsExceptionTrait; +use Zend\ProblemDetails\Exception\ProblemDetailsExceptionInterface; use function sprintf; -class InvalidUrlException extends RuntimeException +class InvalidUrlException extends DomainException implements ProblemDetailsExceptionInterface { + use CommonProblemDetailsExceptionTrait; + + private const TITLE = 'Invalid URL'; + private const TYPE = 'INVALID_URL'; + public static function fromUrl(string $url, ?Throwable $previous = null): self { - $code = $previous !== null ? $previous->getCode() : -1; - return new static(sprintf('Provided URL "%s" is not an existing and valid URL', $url), $code, $previous); + $status = StatusCodeInterface::STATUS_BAD_REQUEST; + $e = new self(sprintf('Provided URL %s is invalid. Try with a different one.', $url), $status, $previous); + + $e->detail = $e->getMessage(); + $e->title = self::TITLE; + $e->type = self::TYPE; + $e->status = $status; + $e->additional = ['url' => $url]; + + return $e; } } diff --git a/module/Core/src/Exception/NonUniqueSlugException.php b/module/Core/src/Exception/NonUniqueSlugException.php index fb7e4503..51beff82 100644 --- a/module/Core/src/Exception/NonUniqueSlugException.php +++ b/module/Core/src/Exception/NonUniqueSlugException.php @@ -4,17 +4,34 @@ declare(strict_types=1); namespace Shlinkio\Shlink\Core\Exception; +use Fig\Http\Message\StatusCodeInterface; +use Zend\ProblemDetails\Exception\CommonProblemDetailsExceptionTrait; +use Zend\ProblemDetails\Exception\ProblemDetailsExceptionInterface; + use function sprintf; -class NonUniqueSlugException extends InvalidArgumentException +class NonUniqueSlugException extends InvalidArgumentException implements ProblemDetailsExceptionInterface { - public static function fromSlug(string $slug, ?string $domain): self + use CommonProblemDetailsExceptionTrait; + + private const TITLE = 'Invalid custom slug'; + private const TYPE = 'INVALID_SLUG'; + + public static function fromSlug(string $slug, ?string $domain = null): self { - $suffix = ''; + $suffix = $domain === null ? '' : sprintf(' for domain "%s"', $domain); + $e = new self(sprintf('Provided slug "%s" is already in use%s.', $slug, $suffix)); + + $e->detail = $e->getMessage(); + $e->title = self::TITLE; + $e->type = self::TYPE; + $e->status = StatusCodeInterface::STATUS_BAD_REQUEST; + $e->additional = ['customSlug' => $slug]; + if ($domain !== null) { - $suffix = sprintf(' for domain "%s"', $domain); + $e->additional['domain'] = $domain; } - return new self(sprintf('Provided slug "%s" is not unique%s.', $slug, $suffix)); + return $e; } } diff --git a/module/Core/src/Exception/ShortUrlNotFoundException.php b/module/Core/src/Exception/ShortUrlNotFoundException.php new file mode 100644 index 00000000..aca1bce9 --- /dev/null +++ b/module/Core/src/Exception/ShortUrlNotFoundException.php @@ -0,0 +1,37 @@ +detail = $e->getMessage(); + $e->title = self::TITLE; + $e->type = self::TYPE; + $e->status = StatusCodeInterface::STATUS_NOT_FOUND; + $e->additional = ['shortCode' => $shortCode]; + + if ($domain !== null) { + $e->additional['domain'] = $domain; + } + + return $e; + } +} diff --git a/module/Core/src/Exception/TagConflictException.php b/module/Core/src/Exception/TagConflictException.php index db26682e..5a624f8f 100644 --- a/module/Core/src/Exception/TagConflictException.php +++ b/module/Core/src/Exception/TagConflictException.php @@ -4,12 +4,32 @@ declare(strict_types=1); namespace Shlinkio\Shlink\Core\Exception; +use Fig\Http\Message\StatusCodeInterface; +use Zend\ProblemDetails\Exception\CommonProblemDetailsExceptionTrait; +use Zend\ProblemDetails\Exception\ProblemDetailsExceptionInterface; + use function sprintf; -class TagConflictException extends RuntimeException +class TagConflictException extends RuntimeException implements ProblemDetailsExceptionInterface { + use CommonProblemDetailsExceptionTrait; + + private const TITLE = 'Tag conflict'; + private const TYPE = 'TAG_CONFLICT'; + public static function fromExistingTag(string $oldName, string $newName): self { - return new self(sprintf('You cannot rename tag %s to %s, because it already exists', $oldName, $newName)); + $e = new self(sprintf('You cannot rename tag %s to %s, because it already exists', $oldName, $newName)); + + $e->detail = $e->getMessage(); + $e->title = self::TITLE; + $e->type = self::TYPE; + $e->status = StatusCodeInterface::STATUS_CONFLICT; + $e->additional = [ + 'oldName' => $oldName, + 'newName' => $newName, + ]; + + return $e; } } diff --git a/module/Core/src/Exception/TagNotFoundException.php b/module/Core/src/Exception/TagNotFoundException.php new file mode 100644 index 00000000..1924e89a --- /dev/null +++ b/module/Core/src/Exception/TagNotFoundException.php @@ -0,0 +1,32 @@ +detail = $e->getMessage(); + $e->title = self::TITLE; + $e->type = self::TYPE; + $e->status = StatusCodeInterface::STATUS_NOT_FOUND; + $e->additional = ['tag' => $tag]; + + return $e; + } +} diff --git a/module/Core/src/Exception/ValidationException.php b/module/Core/src/Exception/ValidationException.php index 1b767594..abceec91 100644 --- a/module/Core/src/Exception/ValidationException.php +++ b/module/Core/src/Exception/ValidationException.php @@ -4,9 +4,13 @@ declare(strict_types=1); namespace Shlinkio\Shlink\Core\Exception; +use Fig\Http\Message\StatusCodeInterface; use Throwable; use Zend\InputFilter\InputFilterInterface; +use Zend\ProblemDetails\Exception\CommonProblemDetailsExceptionTrait; +use Zend\ProblemDetails\Exception\ProblemDetailsExceptionInterface; +use function array_keys; use function Functional\reduce_left; use function is_array; use function print_r; @@ -14,44 +18,59 @@ use function sprintf; use const PHP_EOL; -class ValidationException extends RuntimeException +class ValidationException extends InvalidArgumentException implements ProblemDetailsExceptionInterface { + use CommonProblemDetailsExceptionTrait; + + private const TITLE = 'Invalid data'; + private const TYPE = 'INVALID_ARGUMENT'; + /** @var array */ private $invalidElements; - public function __construct( - string $message = '', - array $invalidElements = [], - int $code = 0, - ?Throwable $previous = null - ) { - $this->invalidElements = $invalidElements; - parent::__construct($message, $code, $previous); - } - public static function fromInputFilter(InputFilterInterface $inputFilter, ?Throwable $prev = null): self { return static::fromArray($inputFilter->getMessages(), $prev); } - private static function fromArray(array $invalidData, ?Throwable $prev = null): self + public static function fromArray(array $invalidData, ?Throwable $prev = null): self { - return new self( - sprintf( - 'Provided data is not valid. These are the messages:%s%s%s', - PHP_EOL, - self::formMessagesToString($invalidData), - PHP_EOL - ), - $invalidData, - -1, - $prev + $status = StatusCodeInterface::STATUS_BAD_REQUEST; + $e = new self('Provided data is not valid', $status, $prev); + + $e->detail = $e->getMessage(); + $e->title = self::TITLE; + $e->type = self::TYPE; + $e->status = StatusCodeInterface::STATUS_BAD_REQUEST; + $e->invalidElements = $invalidData; + $e->additional = ['invalidElements' => array_keys($invalidData)]; + + return $e; + } + + public function getInvalidElements(): array + { + return $this->invalidElements; + } + + public function __toString(): string + { + return sprintf( + '%s %s in %s:%s%s%sStack trace:%s%s', + __CLASS__, + $this->getMessage(), + $this->getFile(), + $this->getLine(), + $this->invalidElementsToString(), + PHP_EOL, + PHP_EOL, + $this->getTraceAsString() ); } - private static function formMessagesToString(array $messages = []): string + private function invalidElementsToString(): string { - return reduce_left($messages, function ($messageSet, $name, $_, string $acc) { + return reduce_left($this->getInvalidElements(), function ($messageSet, string $name, $_, string $acc) { return $acc . sprintf( "\n '%s' => %s", $name, @@ -59,9 +78,4 @@ class ValidationException extends RuntimeException ); }, ''); } - - public function getInvalidElements(): array - { - return $this->invalidElements; - } } diff --git a/module/Core/src/Paginator/Adapter/ShortUrlRepositoryAdapter.php b/module/Core/src/Paginator/Adapter/ShortUrlRepositoryAdapter.php index 80ffb1e8..de382d17 100644 --- a/module/Core/src/Paginator/Adapter/ShortUrlRepositoryAdapter.php +++ b/module/Core/src/Paginator/Adapter/ShortUrlRepositoryAdapter.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Shlinkio\Shlink\Core\Paginator\Adapter; +use Shlinkio\Shlink\Common\Util\DateRange; use Shlinkio\Shlink\Core\Repository\ShortUrlRepositoryInterface; use Zend\Paginator\Adapter\AdapterInterface; @@ -22,17 +23,21 @@ class ShortUrlRepositoryAdapter implements AdapterInterface private $orderBy; /** @var array */ private $tags; + /** @var DateRange|null */ + private $dateRange; public function __construct( ShortUrlRepositoryInterface $repository, $searchTerm = null, array $tags = [], - $orderBy = null + $orderBy = null, + ?DateRange $dateRange = null ) { $this->repository = $repository; $this->searchTerm = $searchTerm !== null ? trim(strip_tags($searchTerm)) : null; $this->orderBy = $orderBy; $this->tags = $tags; + $this->dateRange = $dateRange; } /** @@ -49,7 +54,8 @@ class ShortUrlRepositoryAdapter implements AdapterInterface $offset, $this->searchTerm, $this->tags, - $this->orderBy + $this->orderBy, + $this->dateRange ); } @@ -64,6 +70,6 @@ class ShortUrlRepositoryAdapter implements AdapterInterface */ public function count(): int { - return $this->repository->countList($this->searchTerm, $this->tags); + return $this->repository->countList($this->searchTerm, $this->tags, $this->dateRange); } } diff --git a/module/Core/src/Repository/ShortUrlRepository.php b/module/Core/src/Repository/ShortUrlRepository.php index 47f8f985..ac7b5f50 100644 --- a/module/Core/src/Repository/ShortUrlRepository.php +++ b/module/Core/src/Repository/ShortUrlRepository.php @@ -7,6 +7,7 @@ namespace Shlinkio\Shlink\Core\Repository; use Cake\Chronos\Chronos; use Doctrine\ORM\EntityRepository; use Doctrine\ORM\QueryBuilder; +use Shlinkio\Shlink\Common\Util\DateRange; use Shlinkio\Shlink\Core\Entity\ShortUrl; use function array_column; @@ -27,9 +28,10 @@ class ShortUrlRepository extends EntityRepository implements ShortUrlRepositoryI ?int $offset = null, ?string $searchTerm = null, array $tags = [], - $orderBy = null + $orderBy = null, + ?DateRange $dateRange = null ): array { - $qb = $this->createListQueryBuilder($searchTerm, $tags); + $qb = $this->createListQueryBuilder($searchTerm, $tags, $dateRange); $qb->select('DISTINCT s'); // Set limit and offset @@ -52,15 +54,9 @@ class ShortUrlRepository extends EntityRepository implements ShortUrlRepositoryI private function processOrderByForList(QueryBuilder $qb, $orderBy): array { - // Map public field names to column names - $fieldNameMap = [ - 'originalUrl' => 'longUrl', - 'longUrl' => 'longUrl', - 'shortCode' => 'shortCode', - 'dateCreated' => 'dateCreated', - ]; - $fieldName = is_array($orderBy) ? key($orderBy) : $orderBy; - $order = is_array($orderBy) ? $orderBy[$fieldName] : 'ASC'; + $isArray = is_array($orderBy); + $fieldName = $isArray ? key($orderBy) : $orderBy; + $order = $isArray ? $orderBy[$fieldName] : 'ASC'; if (contains(['visits', 'visitsCount', 'visitCount'], $fieldName)) { $qb->addSelect('COUNT(DISTINCT v) AS totalVisits') @@ -71,26 +67,45 @@ class ShortUrlRepository extends EntityRepository implements ShortUrlRepositoryI return array_column($qb->getQuery()->getResult(), 0); } + // Map public field names to column names + $fieldNameMap = [ + 'originalUrl' => 'longUrl', + 'longUrl' => 'longUrl', + 'shortCode' => 'shortCode', + 'dateCreated' => 'dateCreated', + ]; if (array_key_exists($fieldName, $fieldNameMap)) { $qb->orderBy('s.' . $fieldNameMap[$fieldName], $order); } return $qb->getQuery()->getResult(); } - public function countList(?string $searchTerm = null, array $tags = []): int + public function countList(?string $searchTerm = null, array $tags = [], ?DateRange $dateRange = null): int { - $qb = $this->createListQueryBuilder($searchTerm, $tags); + $qb = $this->createListQueryBuilder($searchTerm, $tags, $dateRange); $qb->select('COUNT(DISTINCT s)'); return (int) $qb->getQuery()->getSingleScalarResult(); } - private function createListQueryBuilder(?string $searchTerm = null, array $tags = []): QueryBuilder - { + private function createListQueryBuilder( + ?string $searchTerm = null, + array $tags = [], + ?DateRange $dateRange = null + ): QueryBuilder { $qb = $this->getEntityManager()->createQueryBuilder(); $qb->from(ShortUrl::class, 's'); $qb->where('1=1'); + if ($dateRange !== null && $dateRange->getStartDate() !== null) { + $qb->andWhere($qb->expr()->gte('s.dateCreated', ':startDate')); + $qb->setParameter('startDate', $dateRange->getStartDate()); + } + if ($dateRange !== null && $dateRange->getEndDate() !== null) { + $qb->andWhere($qb->expr()->lte('s.dateCreated', ':endDate')); + $qb->setParameter('endDate', $dateRange->getEndDate()); + } + // Apply search term to every searchable field if not empty if (! empty($searchTerm)) { // Left join with tags only if no tags were provided. In case of tags, an inner join will be done later @@ -98,14 +113,12 @@ class ShortUrlRepository extends EntityRepository implements ShortUrlRepositoryI $qb->leftJoin('s.tags', 't'); } - $conditions = [ + // Apply search conditions + $qb->andWhere($qb->expr()->orX( $qb->expr()->like('s.longUrl', ':searchPattern'), $qb->expr()->like('s.shortCode', ':searchPattern'), - $qb->expr()->like('t.name', ':searchPattern'), - ]; - - // Unpack and apply search conditions - $qb->andWhere($qb->expr()->orX(...$conditions)); + $qb->expr()->like('t.name', ':searchPattern') + )); $qb->setParameter('searchPattern', '%' . $searchTerm . '%'); } diff --git a/module/Core/src/Repository/ShortUrlRepositoryInterface.php b/module/Core/src/Repository/ShortUrlRepositoryInterface.php index da5cef61..8695021a 100644 --- a/module/Core/src/Repository/ShortUrlRepositoryInterface.php +++ b/module/Core/src/Repository/ShortUrlRepositoryInterface.php @@ -4,14 +4,13 @@ declare(strict_types=1); namespace Shlinkio\Shlink\Core\Repository; -use Doctrine\Common\Persistence\ObjectRepository; +use Doctrine\Persistence\ObjectRepository; +use Shlinkio\Shlink\Common\Util\DateRange; use Shlinkio\Shlink\Core\Entity\ShortUrl; interface ShortUrlRepositoryInterface extends ObjectRepository { /** - * Gets a list of elements using provided filtering data - * * @param string|array|null $orderBy */ public function findList( @@ -19,13 +18,11 @@ interface ShortUrlRepositoryInterface extends ObjectRepository ?int $offset = null, ?string $searchTerm = null, array $tags = [], - $orderBy = null + $orderBy = null, + ?DateRange $dateRange = null ): array; - /** - * Counts the number of elements in a list using provided filtering data - */ - public function countList(?string $searchTerm = null, array $tags = []): int; + public function countList(?string $searchTerm = null, array $tags = [], ?DateRange $dateRange = null): int; public function findOneByShortCode(string $shortCode, ?string $domain = null): ?ShortUrl; diff --git a/module/Core/src/Repository/TagRepositoryInterface.php b/module/Core/src/Repository/TagRepositoryInterface.php index 182df847..e253f7a4 100644 --- a/module/Core/src/Repository/TagRepositoryInterface.php +++ b/module/Core/src/Repository/TagRepositoryInterface.php @@ -4,7 +4,7 @@ declare(strict_types=1); namespace Shlinkio\Shlink\Core\Repository; -use Doctrine\Common\Persistence\ObjectRepository; +use Doctrine\Persistence\ObjectRepository; interface TagRepositoryInterface extends ObjectRepository { diff --git a/module/Core/src/Repository/VisitRepositoryInterface.php b/module/Core/src/Repository/VisitRepositoryInterface.php index a0bbfe99..e70c989e 100644 --- a/module/Core/src/Repository/VisitRepositoryInterface.php +++ b/module/Core/src/Repository/VisitRepositoryInterface.php @@ -4,7 +4,7 @@ declare(strict_types=1); namespace Shlinkio\Shlink\Core\Repository; -use Doctrine\Common\Persistence\ObjectRepository; +use Doctrine\Persistence\ObjectRepository; use Shlinkio\Shlink\Common\Util\DateRange; use Shlinkio\Shlink\Core\Entity\Visit; diff --git a/module/Core/src/Service/ShortUrl/DeleteShortUrlService.php b/module/Core/src/Service/ShortUrl/DeleteShortUrlService.php index 00837cff..c7cfb9c4 100644 --- a/module/Core/src/Service/ShortUrl/DeleteShortUrlService.php +++ b/module/Core/src/Service/ShortUrl/DeleteShortUrlService.php @@ -25,7 +25,7 @@ class DeleteShortUrlService implements DeleteShortUrlServiceInterface } /** - * @throws Exception\InvalidShortCodeException + * @throws Exception\ShortUrlNotFoundException * @throws Exception\DeleteShortUrlException */ public function deleteByShortCode(string $shortCode, bool $ignoreThreshold = false): void diff --git a/module/Core/src/Service/ShortUrl/DeleteShortUrlServiceInterface.php b/module/Core/src/Service/ShortUrl/DeleteShortUrlServiceInterface.php index cd954ae2..b196375d 100644 --- a/module/Core/src/Service/ShortUrl/DeleteShortUrlServiceInterface.php +++ b/module/Core/src/Service/ShortUrl/DeleteShortUrlServiceInterface.php @@ -9,7 +9,7 @@ use Shlinkio\Shlink\Core\Exception; interface DeleteShortUrlServiceInterface { /** - * @throws Exception\InvalidShortCodeException + * @throws Exception\ShortUrlNotFoundException * @throws Exception\DeleteShortUrlException */ public function deleteByShortCode(string $shortCode, bool $ignoreThreshold = false): void; diff --git a/module/Core/src/Service/ShortUrl/FindShortCodeTrait.php b/module/Core/src/Service/ShortUrl/FindShortCodeTrait.php index 47253244..81cc0e84 100644 --- a/module/Core/src/Service/ShortUrl/FindShortCodeTrait.php +++ b/module/Core/src/Service/ShortUrl/FindShortCodeTrait.php @@ -6,14 +6,14 @@ namespace Shlinkio\Shlink\Core\Service\ShortUrl; use Doctrine\ORM\EntityManagerInterface; use Shlinkio\Shlink\Core\Entity\ShortUrl; -use Shlinkio\Shlink\Core\Exception\InvalidShortCodeException; +use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException; trait FindShortCodeTrait { /** * @param string $shortCode * @return ShortUrl - * @throws InvalidShortCodeException + * @throws ShortUrlNotFoundException */ private function findByShortCode(EntityManagerInterface $em, string $shortCode): ShortUrl { @@ -22,7 +22,7 @@ trait FindShortCodeTrait 'shortCode' => $shortCode, ]); if ($shortUrl === null) { - throw InvalidShortCodeException::fromNotFoundShortCode($shortCode); + throw ShortUrlNotFoundException::fromNotFoundShortCode($shortCode); } return $shortUrl; diff --git a/module/Core/src/Service/ShortUrlService.php b/module/Core/src/Service/ShortUrlService.php index 1f3ea73a..15a3b432 100644 --- a/module/Core/src/Service/ShortUrlService.php +++ b/module/Core/src/Service/ShortUrlService.php @@ -5,8 +5,9 @@ declare(strict_types=1); namespace Shlinkio\Shlink\Core\Service; use Doctrine\ORM; +use Shlinkio\Shlink\Common\Util\DateRange; use Shlinkio\Shlink\Core\Entity\ShortUrl; -use Shlinkio\Shlink\Core\Exception\InvalidShortCodeException; +use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException; use Shlinkio\Shlink\Core\Model\ShortUrlMeta; use Shlinkio\Shlink\Core\Paginator\Adapter\ShortUrlRepositoryAdapter; use Shlinkio\Shlink\Core\Repository\ShortUrlRepository; @@ -30,13 +31,19 @@ class ShortUrlService implements ShortUrlServiceInterface /** * @param string[] $tags * @param array|string|null $orderBy + * * @return ShortUrl[]|Paginator */ - public function listShortUrls(int $page = 1, ?string $searchQuery = null, array $tags = [], $orderBy = null) - { + public function listShortUrls( + int $page = 1, + ?string $searchQuery = null, + array $tags = [], + $orderBy = null, + ?DateRange $dateRange = null + ) { /** @var ShortUrlRepository $repo */ $repo = $this->em->getRepository(ShortUrl::class); - $paginator = new Paginator(new ShortUrlRepositoryAdapter($repo, $searchQuery, $tags, $orderBy)); + $paginator = new Paginator(new ShortUrlRepositoryAdapter($repo, $searchQuery, $tags, $orderBy, $dateRange)); $paginator->setItemCountPerPage(ShortUrlRepositoryAdapter::ITEMS_PER_PAGE) ->setCurrentPageNumber($page); @@ -45,7 +52,7 @@ class ShortUrlService implements ShortUrlServiceInterface /** * @param string[] $tags - * @throws InvalidShortCodeException + * @throws ShortUrlNotFoundException */ public function setTagsByShortCode(string $shortCode, array $tags = []): ShortUrl { @@ -57,16 +64,14 @@ class ShortUrlService implements ShortUrlServiceInterface } /** - * @throws InvalidShortCodeException + * @throws ShortUrlNotFoundException */ public function updateMetadataByShortCode(string $shortCode, ShortUrlMeta $shortUrlMeta): ShortUrl { $shortUrl = $this->findByShortCode($this->em, $shortCode); $shortUrl->updateMeta($shortUrlMeta); - /** @var ORM\EntityManager $em */ - $em = $this->em; - $em->flush($shortUrl); + $this->em->flush(); return $shortUrl; } diff --git a/module/Core/src/Service/ShortUrlServiceInterface.php b/module/Core/src/Service/ShortUrlServiceInterface.php index e519f7c9..6e3fe199 100644 --- a/module/Core/src/Service/ShortUrlServiceInterface.php +++ b/module/Core/src/Service/ShortUrlServiceInterface.php @@ -4,8 +4,9 @@ declare(strict_types=1); namespace Shlinkio\Shlink\Core\Service; +use Shlinkio\Shlink\Common\Util\DateRange; use Shlinkio\Shlink\Core\Entity\ShortUrl; -use Shlinkio\Shlink\Core\Exception\InvalidShortCodeException; +use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException; use Shlinkio\Shlink\Core\Model\ShortUrlMeta; use Zend\Paginator\Paginator; @@ -14,18 +15,25 @@ interface ShortUrlServiceInterface /** * @param string[] $tags * @param array|string|null $orderBy + * * @return ShortUrl[]|Paginator */ - public function listShortUrls(int $page = 1, ?string $searchQuery = null, array $tags = [], $orderBy = null); + public function listShortUrls( + int $page = 1, + ?string $searchQuery = null, + array $tags = [], + $orderBy = null, + ?DateRange $dateRange = null + ); /** * @param string[] $tags - * @throws InvalidShortCodeException + * @throws ShortUrlNotFoundException */ public function setTagsByShortCode(string $shortCode, array $tags = []): ShortUrl; /** - * @throws InvalidShortCodeException + * @throws ShortUrlNotFoundException */ public function updateMetadataByShortCode(string $shortCode, ShortUrlMeta $shortUrlMeta): ShortUrl; } diff --git a/module/Core/src/Service/Tag/TagService.php b/module/Core/src/Service/Tag/TagService.php index 4a75a061..672f0b05 100644 --- a/module/Core/src/Service/Tag/TagService.php +++ b/module/Core/src/Service/Tag/TagService.php @@ -7,8 +7,8 @@ namespace Shlinkio\Shlink\Core\Service\Tag; use Doctrine\Common\Collections\Collection; use Doctrine\ORM; use Shlinkio\Shlink\Core\Entity\Tag; -use Shlinkio\Shlink\Core\Exception\EntityDoesNotExistException; use Shlinkio\Shlink\Core\Exception\TagConflictException; +use Shlinkio\Shlink\Core\Exception\TagNotFoundException; use Shlinkio\Shlink\Core\Repository\TagRepository; use Shlinkio\Shlink\Core\Util\TagManagerTrait; @@ -36,8 +36,7 @@ class TagService implements TagServiceInterface } /** - * @param array $tagNames - * @return void + * @param string[] $tagNames */ public function deleteTags(array $tagNames): void { @@ -61,23 +60,18 @@ class TagService implements TagServiceInterface } /** - * @param string $oldName - * @param string $newName - * @return Tag - * @throws EntityDoesNotExistException + * @throws TagNotFoundException * @throws TagConflictException - * @throws ORM\OptimisticLockException */ - public function renameTag($oldName, $newName): Tag + public function renameTag(string $oldName, string $newName): Tag { /** @var TagRepository $repo */ $repo = $this->em->getRepository(Tag::class); - $criteria = ['name' => $oldName]; /** @var Tag|null $tag */ - $tag = $repo->findOneBy($criteria); + $tag = $repo->findOneBy(['name' => $oldName]); if ($tag === null) { - throw EntityDoesNotExistException::createFromEntityAndConditions(Tag::class, $criteria); + throw TagNotFoundException::fromTag($oldName); } $newNameExists = $newName !== $oldName && $repo->count(['name' => $newName]) > 0; @@ -86,10 +80,7 @@ class TagService implements TagServiceInterface } $tag->rename($newName); - - /** @var ORM\EntityManager $em */ - $em = $this->em; - $em->flush($tag); + $this->em->flush(); return $tag; } diff --git a/module/Core/src/Service/Tag/TagServiceInterface.php b/module/Core/src/Service/Tag/TagServiceInterface.php index 942da3a6..16da503c 100644 --- a/module/Core/src/Service/Tag/TagServiceInterface.php +++ b/module/Core/src/Service/Tag/TagServiceInterface.php @@ -6,8 +6,8 @@ namespace Shlinkio\Shlink\Core\Service\Tag; use Doctrine\Common\Collections\Collection; use Shlinkio\Shlink\Core\Entity\Tag; -use Shlinkio\Shlink\Core\Exception\EntityDoesNotExistException; use Shlinkio\Shlink\Core\Exception\TagConflictException; +use Shlinkio\Shlink\Core\Exception\TagNotFoundException; interface TagServiceInterface { @@ -18,24 +18,18 @@ interface TagServiceInterface /** * @param string[] $tagNames - * @return void */ public function deleteTags(array $tagNames): void; /** - * Provided a list of tag names, creates all that do not exist yet - * * @param string[] $tagNames * @return Collection|Tag[] */ public function createTags(array $tagNames): Collection; /** - * @param string $oldName - * @param string $newName - * @return Tag - * @throws EntityDoesNotExistException + * @throws TagNotFoundException * @throws TagConflictException */ - public function renameTag($oldName, $newName): Tag; + public function renameTag(string $oldName, string $newName): Tag; } diff --git a/module/Core/src/Service/UrlShortener.php b/module/Core/src/Service/UrlShortener.php index 6b04d63a..70112bd7 100644 --- a/module/Core/src/Service/UrlShortener.php +++ b/module/Core/src/Service/UrlShortener.php @@ -8,10 +8,9 @@ use Doctrine\ORM\EntityManagerInterface; use Psr\Http\Message\UriInterface; use Shlinkio\Shlink\Core\Domain\Resolver\PersistenceDomainResolver; use Shlinkio\Shlink\Core\Entity\ShortUrl; -use Shlinkio\Shlink\Core\Exception\EntityDoesNotExistException; -use Shlinkio\Shlink\Core\Exception\InvalidShortCodeException; use Shlinkio\Shlink\Core\Exception\InvalidUrlException; use Shlinkio\Shlink\Core\Exception\NonUniqueSlugException; +use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException; use Shlinkio\Shlink\Core\Model\ShortUrlMeta; use Shlinkio\Shlink\Core\Options\UrlShortenerOptions; use Shlinkio\Shlink\Core\Repository\ShortUrlRepository; @@ -130,8 +129,8 @@ class UrlShortener implements UrlShortenerInterface } /** - * @throws InvalidShortCodeException - * @throws EntityDoesNotExistException + * @throws ShortUrlNotFoundException + * @fixme Move this method to a different service */ public function shortCodeToUrl(string $shortCode, ?string $domain = null): ShortUrl { @@ -139,10 +138,7 @@ class UrlShortener implements UrlShortenerInterface $shortUrlRepo = $this->em->getRepository(ShortUrl::class); $shortUrl = $shortUrlRepo->findOneByShortCode($shortCode, $domain); if ($shortUrl === null) { - throw EntityDoesNotExistException::createFromEntityAndConditions(ShortUrl::class, [ - 'shortCode' => $shortCode, - 'domain' => $domain, - ]); + throw ShortUrlNotFoundException::fromNotFoundShortCode($shortCode, $domain); } return $shortUrl; diff --git a/module/Core/src/Service/UrlShortenerInterface.php b/module/Core/src/Service/UrlShortenerInterface.php index 74d626fc..ee9cc343 100644 --- a/module/Core/src/Service/UrlShortenerInterface.php +++ b/module/Core/src/Service/UrlShortenerInterface.php @@ -6,11 +6,9 @@ namespace Shlinkio\Shlink\Core\Service; use Psr\Http\Message\UriInterface; use Shlinkio\Shlink\Core\Entity\ShortUrl; -use Shlinkio\Shlink\Core\Exception\EntityDoesNotExistException; -use Shlinkio\Shlink\Core\Exception\InvalidShortCodeException; use Shlinkio\Shlink\Core\Exception\InvalidUrlException; use Shlinkio\Shlink\Core\Exception\NonUniqueSlugException; -use Shlinkio\Shlink\Core\Exception\RuntimeException; +use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException; use Shlinkio\Shlink\Core\Model\ShortUrlMeta; interface UrlShortenerInterface @@ -19,13 +17,11 @@ interface UrlShortenerInterface * @param string[] $tags * @throws NonUniqueSlugException * @throws InvalidUrlException - * @throws RuntimeException */ public function urlToShortCode(UriInterface $url, array $tags, ShortUrlMeta $meta): ShortUrl; /** - * @throws InvalidShortCodeException - * @throws EntityDoesNotExistException + * @throws ShortUrlNotFoundException */ public function shortCodeToUrl(string $shortCode, ?string $domain = null): ShortUrl; } diff --git a/module/Core/src/Service/VisitsTracker.php b/module/Core/src/Service/VisitsTracker.php index ebfdf778..612ad4ee 100644 --- a/module/Core/src/Service/VisitsTracker.php +++ b/module/Core/src/Service/VisitsTracker.php @@ -9,15 +9,13 @@ use Psr\EventDispatcher\EventDispatcherInterface; use Shlinkio\Shlink\Core\Entity\ShortUrl; use Shlinkio\Shlink\Core\Entity\Visit; use Shlinkio\Shlink\Core\EventDispatcher\ShortUrlVisited; -use Shlinkio\Shlink\Core\Exception\InvalidArgumentException; +use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException; use Shlinkio\Shlink\Core\Model\Visitor; use Shlinkio\Shlink\Core\Model\VisitsParams; use Shlinkio\Shlink\Core\Paginator\Adapter\VisitsPaginatorAdapter; use Shlinkio\Shlink\Core\Repository\VisitRepository; use Zend\Paginator\Paginator; -use function sprintf; - class VisitsTracker implements VisitsTrackerInterface { /** @var ORM\EntityManagerInterface */ @@ -43,10 +41,8 @@ class VisitsTracker implements VisitsTrackerInterface $visit = new Visit($shortUrl, $visitor); - /** @var ORM\EntityManager $em */ - $em = $this->em; - $em->persist($visit); - $em->flush($visit); + $this->em->persist($visit); + $this->em->flush(); $this->eventDispatcher->dispatch(new ShortUrlVisited($visit->getId())); } @@ -55,14 +51,14 @@ class VisitsTracker implements VisitsTrackerInterface * Returns the visits on certain short code * * @return Visit[]|Paginator - * @throws InvalidArgumentException + * @throws ShortUrlNotFoundException */ public function info(string $shortCode, VisitsParams $params): Paginator { /** @var ORM\EntityRepository $repo */ $repo = $this->em->getRepository(ShortUrl::class); if ($repo->count(['shortCode' => $shortCode]) < 1) { - throw new InvalidArgumentException(sprintf('Short code "%s" not found', $shortCode)); + throw ShortUrlNotFoundException::fromNotFoundShortCode($shortCode); } /** @var VisitRepository $repo */ diff --git a/module/Core/src/Service/VisitsTrackerInterface.php b/module/Core/src/Service/VisitsTrackerInterface.php index 03af8299..2786d23b 100644 --- a/module/Core/src/Service/VisitsTrackerInterface.php +++ b/module/Core/src/Service/VisitsTrackerInterface.php @@ -5,7 +5,7 @@ declare(strict_types=1); namespace Shlinkio\Shlink\Core\Service; use Shlinkio\Shlink\Core\Entity\Visit; -use Shlinkio\Shlink\Core\Exception\InvalidArgumentException; +use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException; use Shlinkio\Shlink\Core\Model\Visitor; use Shlinkio\Shlink\Core\Model\VisitsParams; use Zend\Paginator\Paginator; @@ -21,7 +21,7 @@ interface VisitsTrackerInterface * Returns the visits on certain short code * * @return Visit[]|Paginator - * @throws InvalidArgumentException + * @throws ShortUrlNotFoundException */ public function info(string $shortCode, VisitsParams $params): Paginator; } diff --git a/module/Core/src/Transformer/ShortUrlDataTransformer.php b/module/Core/src/Transformer/ShortUrlDataTransformer.php index 4562782f..348ff0d5 100644 --- a/module/Core/src/Transformer/ShortUrlDataTransformer.php +++ b/module/Core/src/Transformer/ShortUrlDataTransformer.php @@ -23,11 +23,11 @@ class ShortUrlDataTransformer implements DataTransformerInterface /** * @param ShortUrl $shortUrl */ - public function transform($shortUrl): array + public function transform($shortUrl, bool $includeDeprecated = true): array { $longUrl = $shortUrl->getLongUrl(); - return [ + $rawData = [ 'shortCode' => $shortUrl->getShortCode(), 'shortUrl' => $shortUrl->toString($this->domainConfig), 'longUrl' => $longUrl, @@ -35,10 +35,13 @@ class ShortUrlDataTransformer implements DataTransformerInterface 'visitsCount' => $shortUrl->getVisitsCount(), 'tags' => invoke($shortUrl->getTags(), '__toString'), 'meta' => $this->buildMeta($shortUrl), - - // Deprecated - 'originalUrl' => $longUrl, ]; + + if ($includeDeprecated) { + $rawData['originalUrl'] = $longUrl; + } + + return $rawData; } private function buildMeta(ShortUrl $shortUrl): array diff --git a/module/Core/src/Util/UrlValidator.php b/module/Core/src/Util/UrlValidator.php index a3ffe0d8..db7c6c2a 100644 --- a/module/Core/src/Util/UrlValidator.php +++ b/module/Core/src/Util/UrlValidator.php @@ -5,20 +5,12 @@ declare(strict_types=1); namespace Shlinkio\Shlink\Core\Util; use Fig\Http\Message\RequestMethodInterface; -use Fig\Http\Message\StatusCodeInterface; use GuzzleHttp\ClientInterface; use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\RequestOptions; use Shlinkio\Shlink\Core\Exception\InvalidUrlException; -use Zend\Diactoros\Uri; -use function Functional\contains; -use function idn_to_ascii; - -use const IDNA_DEFAULT; -use const INTL_IDNA_VARIANT_UTS46; - -class UrlValidator implements UrlValidatorInterface, RequestMethodInterface, StatusCodeInterface +class UrlValidator implements UrlValidatorInterface, RequestMethodInterface { private const MAX_REDIRECTS = 15; @@ -35,39 +27,12 @@ class UrlValidator implements UrlValidatorInterface, RequestMethodInterface, Sta */ public function validateUrl(string $url): void { - $this->doValidateUrl($url); - } - - /** - * @throws InvalidUrlException - */ - private function doValidateUrl(string $url, int $redirectNum = 1): void - { - // FIXME Guzzle is about to add support for this https://github.com/guzzle/guzzle/pull/2286 - // Remove custom implementation and manual redirect handling when Guzzle's PR is merged - $uri = new Uri($url); - $originalHost = $uri->getHost(); - $normalizedHost = idn_to_ascii($originalHost, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46); - if ($originalHost !== $normalizedHost) { - $uri = $uri->withHost($normalizedHost); - } - try { - $resp = $this->httpClient->request(self::METHOD_GET, (string) $uri, [ -// RequestOptions::ALLOW_REDIRECTS => ['max' => self::MAX_REDIRECTS], - RequestOptions::ALLOW_REDIRECTS => false, + $this->httpClient->request(self::METHOD_GET, $url, [ + RequestOptions::ALLOW_REDIRECTS => ['max' => self::MAX_REDIRECTS], ]); - - if ($redirectNum < self::MAX_REDIRECTS && $this->statusIsRedirect($resp->getStatusCode())) { - $this->doValidateUrl($resp->getHeaderLine('Location'), $redirectNum + 1); - } } catch (GuzzleException $e) { throw InvalidUrlException::fromUrl($url, $e); } } - - private function statusIsRedirect(int $statusCode): bool - { - return contains([self::STATUS_MOVED_PERMANENTLY, self::STATUS_FOUND], $statusCode); - } } diff --git a/module/Core/test-db/Repository/ShortUrlRepositoryTest.php b/module/Core/test-db/Repository/ShortUrlRepositoryTest.php index f3913ea2..2006623a 100644 --- a/module/Core/test-db/Repository/ShortUrlRepositoryTest.php +++ b/module/Core/test-db/Repository/ShortUrlRepositoryTest.php @@ -6,6 +6,8 @@ namespace ShlinkioTest\Shlink\Core\Repository; use Cake\Chronos\Chronos; use Doctrine\Common\Collections\ArrayCollection; +use ReflectionObject; +use Shlinkio\Shlink\Common\Util\DateRange; use Shlinkio\Shlink\Core\Entity\Domain; use Shlinkio\Shlink\Core\Entity\ShortUrl; use Shlinkio\Shlink\Core\Entity\Tag; @@ -108,7 +110,7 @@ class ShortUrlRepositoryTest extends DatabaseTestCase } /** @test */ - public function findListProperlyFiltersByTagAndSearchTerm(): void + public function findListProperlyFiltersResult(): void { $tag = new Tag('bar'); $this->getEntityManager()->persist($tag); @@ -124,12 +126,17 @@ class ShortUrlRepositoryTest extends DatabaseTestCase $this->getEntityManager()->persist($bar); $foo2 = new ShortUrl('foo_2'); + $ref = new ReflectionObject($foo2); + $dateProp = $ref->getProperty('dateCreated'); + $dateProp->setAccessible(true); + $dateProp->setValue($foo2, Chronos::now()->subDays(5)); $this->getEntityManager()->persist($foo2); $this->getEntityManager()->flush(); $result = $this->repo->findList(null, null, 'foo', ['bar']); $this->assertCount(1, $result); + $this->assertEquals(1, $this->repo->countList('foo', ['bar'])); $this->assertSame($foo, $result[0]); $result = $this->repo->findList(); @@ -141,12 +148,22 @@ class ShortUrlRepositoryTest extends DatabaseTestCase $result = $this->repo->findList(2, 1); $this->assertCount(2, $result); - $result = $this->repo->findList(2, 2); - $this->assertCount(1, $result); + $this->assertCount(1, $this->repo->findList(2, 2)); $result = $this->repo->findList(null, null, null, [], ['visits' => 'DESC']); $this->assertCount(3, $result); $this->assertSame($bar, $result[0]); + + $result = $this->repo->findList(null, null, null, [], null, new DateRange(null, Chronos::now()->subDays(2))); + $this->assertCount(1, $result); + $this->assertEquals(1, $this->repo->countList(null, [], new DateRange(null, Chronos::now()->subDays(2)))); + $this->assertSame($foo2, $result[0]); + + $this->assertCount( + 2, + $this->repo->findList(null, null, null, [], null, new DateRange(Chronos::now()->subDays(2))) + ); + $this->assertEquals(2, $this->repo->countList(null, [], new DateRange(Chronos::now()->subDays(2)))); } /** @test */ diff --git a/module/Core/test/Action/PreviewActionTest.php b/module/Core/test/Action/PreviewActionTest.php index bb52ec0e..e2cb089c 100644 --- a/module/Core/test/Action/PreviewActionTest.php +++ b/module/Core/test/Action/PreviewActionTest.php @@ -11,8 +11,7 @@ use Prophecy\Prophecy\ObjectProphecy; use Psr\Http\Server\RequestHandlerInterface; use Shlinkio\Shlink\Core\Action\PreviewAction; use Shlinkio\Shlink\Core\Entity\ShortUrl; -use Shlinkio\Shlink\Core\Exception\EntityDoesNotExistException; -use Shlinkio\Shlink\Core\Exception\InvalidShortCodeException; +use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException; use Shlinkio\Shlink\Core\Service\UrlShortener; use Shlinkio\Shlink\PreviewGenerator\Service\PreviewGenerator; use Zend\Diactoros\Response; @@ -38,19 +37,6 @@ class PreviewActionTest extends TestCase $this->action = new PreviewAction($this->previewGenerator->reveal(), $this->urlShortener->reveal()); } - /** @test */ - public function invalidShortCodeFallsBackToNextMiddleware(): void - { - $shortCode = 'abc123'; - $this->urlShortener->shortCodeToUrl($shortCode)->willThrow(EntityDoesNotExistException::class) - ->shouldBeCalledOnce(); - $delegate = $this->prophesize(RequestHandlerInterface::class); - $delegate->handle(Argument::cetera())->shouldBeCalledOnce() - ->willReturn(new Response()); - - $this->action->process((new ServerRequest())->withAttribute('shortCode', $shortCode), $delegate->reveal()); - } - /** @test */ public function correctShortCodeReturnsImageResponse(): void { @@ -74,7 +60,7 @@ class PreviewActionTest extends TestCase public function invalidShortCodeExceptionFallsBackToNextMiddleware(): void { $shortCode = 'abc123'; - $this->urlShortener->shortCodeToUrl($shortCode)->willThrow(InvalidShortCodeException::class) + $this->urlShortener->shortCodeToUrl($shortCode)->willThrow(ShortUrlNotFoundException::class) ->shouldBeCalledOnce(); $delegate = $this->prophesize(RequestHandlerInterface::class); $process = $delegate->handle(Argument::any())->willReturn(new Response()); diff --git a/module/Core/test/Action/QrCodeActionTest.php b/module/Core/test/Action/QrCodeActionTest.php index ddb062dd..6327ad69 100644 --- a/module/Core/test/Action/QrCodeActionTest.php +++ b/module/Core/test/Action/QrCodeActionTest.php @@ -11,8 +11,7 @@ use Psr\Http\Server\RequestHandlerInterface; use Shlinkio\Shlink\Common\Response\QrCodeResponse; use Shlinkio\Shlink\Core\Action\QrCodeAction; use Shlinkio\Shlink\Core\Entity\ShortUrl; -use Shlinkio\Shlink\Core\Exception\EntityDoesNotExistException; -use Shlinkio\Shlink\Core\Exception\InvalidShortCodeException; +use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException; use Shlinkio\Shlink\Core\Service\UrlShortener; use Zend\Diactoros\Response; use Zend\Diactoros\ServerRequest; @@ -39,7 +38,7 @@ class QrCodeActionTest extends TestCase public function aNotFoundShortCodeWillDelegateIntoNextMiddleware(): void { $shortCode = 'abc123'; - $this->urlShortener->shortCodeToUrl($shortCode, '')->willThrow(EntityDoesNotExistException::class) + $this->urlShortener->shortCodeToUrl($shortCode, '')->willThrow(ShortUrlNotFoundException::class) ->shouldBeCalledOnce(); $delegate = $this->prophesize(RequestHandlerInterface::class); $process = $delegate->handle(Argument::any())->willReturn(new Response()); @@ -53,7 +52,7 @@ class QrCodeActionTest extends TestCase public function anInvalidShortCodeWillReturnNotFoundResponse(): void { $shortCode = 'abc123'; - $this->urlShortener->shortCodeToUrl($shortCode, '')->willThrow(InvalidShortCodeException::class) + $this->urlShortener->shortCodeToUrl($shortCode, '')->willThrow(ShortUrlNotFoundException::class) ->shouldBeCalledOnce(); $delegate = $this->prophesize(RequestHandlerInterface::class); $process = $delegate->handle(Argument::any())->willReturn(new Response()); diff --git a/module/Core/test/Action/RedirectActionTest.php b/module/Core/test/Action/RedirectActionTest.php index a65927eb..55342cb5 100644 --- a/module/Core/test/Action/RedirectActionTest.php +++ b/module/Core/test/Action/RedirectActionTest.php @@ -10,7 +10,7 @@ use Prophecy\Prophecy\ObjectProphecy; use Psr\Http\Server\RequestHandlerInterface; use Shlinkio\Shlink\Core\Action\RedirectAction; use Shlinkio\Shlink\Core\Entity\ShortUrl; -use Shlinkio\Shlink\Core\Exception\EntityDoesNotExistException; +use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException; use Shlinkio\Shlink\Core\Options; use Shlinkio\Shlink\Core\Service\UrlShortener; use Shlinkio\Shlink\Core\Service\VisitsTracker; @@ -76,7 +76,7 @@ class RedirectActionTest extends TestCase public function nextMiddlewareIsInvokedIfLongUrlIsNotFound(): void { $shortCode = 'abc123'; - $this->urlShortener->shortCodeToUrl($shortCode, '')->willThrow(EntityDoesNotExistException::class) + $this->urlShortener->shortCodeToUrl($shortCode, '')->willThrow(ShortUrlNotFoundException::class) ->shouldBeCalledOnce(); $this->visitTracker->track(Argument::cetera())->shouldNotBeCalled(); diff --git a/module/Core/test/Config/SimplifiedConfigParserTest.php b/module/Core/test/Config/SimplifiedConfigParserTest.php index 20afab7f..76ba9b1b 100644 --- a/module/Core/test/Config/SimplifiedConfigParserTest.php +++ b/module/Core/test/Config/SimplifiedConfigParserTest.php @@ -53,6 +53,10 @@ class SimplifiedConfigParserTest extends TestCase ], 'base_path' => '/foo/bar', 'task_worker_num' => 50, + 'visits_webhooks' => [ + 'http://my-api.com/api/v2.3/notify', + 'https://third-party.io/foo', + ], ]; $expected = [ 'app_options' => [ @@ -76,6 +80,10 @@ class SimplifiedConfigParserTest extends TestCase 'hostname' => 'doma.in', ], 'validate_url' => false, + 'visits_webhooks' => [ + 'http://my-api.com/api/v2.3/notify', + 'https://third-party.io/foo', + ], ], 'delete_short_urls' => [ diff --git a/module/Core/test/Domain/Resolver/PersistenceDomainResolverTest.php b/module/Core/test/Domain/Resolver/PersistenceDomainResolverTest.php index be0640b6..4ba796ab 100644 --- a/module/Core/test/Domain/Resolver/PersistenceDomainResolverTest.php +++ b/module/Core/test/Domain/Resolver/PersistenceDomainResolverTest.php @@ -4,8 +4,8 @@ declare(strict_types=1); namespace ShlinkioTest\Shlink\Core\Domain\Resolver; -use Doctrine\Common\Persistence\ObjectRepository; use Doctrine\ORM\EntityManagerInterface; +use Doctrine\Persistence\ObjectRepository; use PHPUnit\Framework\TestCase; use Prophecy\Prophecy\ObjectProphecy; use Shlinkio\Shlink\Core\Domain\Resolver\PersistenceDomainResolver; diff --git a/module/Core/test/ErrorHandler/NotFoundRedirectHandlerTest.php b/module/Core/test/ErrorHandler/NotFoundRedirectHandlerTest.php new file mode 100644 index 00000000..b7796e61 --- /dev/null +++ b/module/Core/test/ErrorHandler/NotFoundRedirectHandlerTest.php @@ -0,0 +1,101 @@ +redirectOptions = new NotFoundRedirectOptions(); + $this->middleware = new NotFoundRedirectHandler($this->redirectOptions, ''); + } + + /** + * @test + * @dataProvider provideRedirects + */ + public function expectedRedirectionIsReturnedDependingOnTheCase( + ServerRequestInterface $request, + string $expectedRedirectTo + ): void { + $this->redirectOptions->invalidShortUrl = 'invalidShortUrl'; + $this->redirectOptions->regular404 = 'regular404'; + $this->redirectOptions->baseUrl = 'baseUrl'; + + $next = $this->prophesize(RequestHandlerInterface::class); + $handle = $next->handle($request)->willReturn(new Response()); + + $resp = $this->middleware->process($request, $next->reveal()); + + $this->assertInstanceOf(Response\RedirectResponse::class, $resp); + $this->assertEquals($expectedRedirectTo, $resp->getHeaderLine('Location')); + $handle->shouldNotHaveBeenCalled(); + } + + public function provideRedirects(): iterable + { + yield 'base URL with trailing slash' => [ + ServerRequestFactory::fromGlobals()->withUri(new Uri('/')), + 'baseUrl', + ]; + yield 'base URL without trailing slash' => [ + ServerRequestFactory::fromGlobals()->withUri(new Uri('')), + 'baseUrl', + ]; + yield 'regular 404' => [ + ServerRequestFactory::fromGlobals()->withUri(new Uri('/foo/bar')), + 'regular404', + ]; + yield 'invalid short URL' => [ + ServerRequestFactory::fromGlobals() + ->withAttribute( + RouteResult::class, + RouteResult::fromRoute( + new Route( + '', + $this->prophesize(MiddlewareInterface::class)->reveal(), + ['GET'], + RedirectAction::class + ) + ) + ) + ->withUri(new Uri('/abc123')), + 'invalidShortUrl', + ]; + } + + /** @test */ + public function nextMiddlewareIsInvokedWhenNotRedirectNeedsToOccur(): void + { + $req = ServerRequestFactory::fromGlobals(); + $resp = new Response(); + + $next = $this->prophesize(RequestHandlerInterface::class); + $handle = $next->handle($req)->willReturn($resp); + + $result = $this->middleware->process($req, $next->reveal()); + + $this->assertSame($resp, $result); + $handle->shouldHaveBeenCalledOnce(); + } +} diff --git a/module/Core/test/ErrorHandler/NotFoundTemplateHandlerTest.php b/module/Core/test/ErrorHandler/NotFoundTemplateHandlerTest.php new file mode 100644 index 00000000..7d763448 --- /dev/null +++ b/module/Core/test/ErrorHandler/NotFoundTemplateHandlerTest.php @@ -0,0 +1,59 @@ +renderer = $this->prophesize(TemplateRendererInterface::class); + $this->handler = new NotFoundTemplateHandler($this->renderer->reveal()); + } + + /** + * @test + * @dataProvider provideTemplates + */ + public function properErrorTemplateIsRendered(ServerRequestInterface $request, string $expectedTemplate): void + { + $request = $request->withHeader('Accept', 'text/html'); + $render = $this->renderer->render($expectedTemplate)->willReturn(''); + + $resp = $this->handler->handle($request); + + $this->assertInstanceOf(Response\HtmlResponse::class, $resp); + $render->shouldHaveBeenCalledOnce(); + } + + public function provideTemplates(): iterable + { + $request = ServerRequestFactory::fromGlobals(); + + yield [$request, NotFoundTemplateHandler::NOT_FOUND_TEMPLATE]; + yield [ + $request->withAttribute( + RouteResult::class, + RouteResult::fromRoute(new Route('', $this->prophesize(MiddlewareInterface::class)->reveal())) + ), + NotFoundTemplateHandler::INVALID_SHORT_CODE_TEMPLATE, + ]; + } +} diff --git a/module/Core/test/EventDispatcher/LocateShortUrlVisitTest.php b/module/Core/test/EventDispatcher/LocateShortUrlVisitTest.php index 14318749..a451ddea 100644 --- a/module/Core/test/EventDispatcher/LocateShortUrlVisitTest.php +++ b/module/Core/test/EventDispatcher/LocateShortUrlVisitTest.php @@ -8,6 +8,7 @@ use Doctrine\ORM\EntityManagerInterface; use PHPUnit\Framework\TestCase; use Prophecy\Argument; use Prophecy\Prophecy\ObjectProphecy; +use Psr\EventDispatcher\EventDispatcherInterface; use Psr\Log\LoggerInterface; use Shlinkio\Shlink\CLI\Exception\GeolocationDbUpdateFailedException; use Shlinkio\Shlink\CLI\Util\GeolocationDbUpdaterInterface; @@ -17,6 +18,7 @@ use Shlinkio\Shlink\Core\Entity\Visit; use Shlinkio\Shlink\Core\Entity\VisitLocation; use Shlinkio\Shlink\Core\EventDispatcher\LocateShortUrlVisit; use Shlinkio\Shlink\Core\EventDispatcher\ShortUrlVisited; +use Shlinkio\Shlink\Core\EventDispatcher\VisitLocated; use Shlinkio\Shlink\Core\Model\Visitor; use Shlinkio\Shlink\Core\Visit\Model\UnknownVisitLocation; use Shlinkio\Shlink\IpGeolocation\Exception\WrongIpException; @@ -35,6 +37,8 @@ class LocateShortUrlVisitTest extends TestCase private $logger; /** @var ObjectProphecy */ private $dbUpdater; + /** @var ObjectProphecy */ + private $eventDispatcher; public function setUp(): void { @@ -42,12 +46,14 @@ class LocateShortUrlVisitTest extends TestCase $this->em = $this->prophesize(EntityManagerInterface::class); $this->logger = $this->prophesize(LoggerInterface::class); $this->dbUpdater = $this->prophesize(GeolocationDbUpdaterInterface::class); + $this->eventDispatcher = $this->prophesize(EventDispatcherInterface::class); $this->locateVisit = new LocateShortUrlVisit( $this->ipLocationResolver->reveal(), $this->em->reveal(), $this->logger->reveal(), - $this->dbUpdater->reveal() + $this->dbUpdater->reveal(), + $this->eventDispatcher->reveal() ); } @@ -56,14 +62,19 @@ class LocateShortUrlVisitTest extends TestCase { $event = new ShortUrlVisited('123'); $findVisit = $this->em->find(Visit::class, '123')->willReturn(null); - $logWarning = $this->logger->warning('Tried to locate visit with id "123", but it does not exist.'); + $logWarning = $this->logger->warning('Tried to locate visit with id "{visitId}", but it does not exist.', [ + 'visitId' => 123, + ]); + $dispatch = $this->eventDispatcher->dispatch(new VisitLocated('123'))->will(function () { + }); ($this->locateVisit)($event); $findVisit->shouldHaveBeenCalledOnce(); - $this->em->flush(Argument::cetera())->shouldNotHaveBeenCalled(); + $this->em->flush()->shouldNotHaveBeenCalled(); $this->ipLocationResolver->resolveIpLocation(Argument::cetera())->shouldNotHaveBeenCalled(); $logWarning->shouldHaveBeenCalled(); + $dispatch->shouldNotHaveBeenCalled(); } /** @test */ @@ -77,16 +88,19 @@ class LocateShortUrlVisitTest extends TestCase WrongIpException::class ); $logWarning = $this->logger->warning( - Argument::containingString('Tried to locate visit with id "123", but its address seems to be wrong.'), + Argument::containingString('Tried to locate visit with id "{visitId}", but its address seems to be wrong.'), Argument::type('array') ); + $dispatch = $this->eventDispatcher->dispatch(new VisitLocated('123'))->will(function () { + }); ($this->locateVisit)($event); $findVisit->shouldHaveBeenCalledOnce(); $resolveLocation->shouldHaveBeenCalledOnce(); $logWarning->shouldHaveBeenCalled(); - $this->em->flush(Argument::cetera())->shouldNotHaveBeenCalled(); + $this->em->flush()->shouldNotHaveBeenCalled(); + $dispatch->shouldHaveBeenCalledOnce(); } /** @@ -97,9 +111,11 @@ class LocateShortUrlVisitTest extends TestCase { $event = new ShortUrlVisited('123'); $findVisit = $this->em->find(Visit::class, '123')->willReturn($visit); - $flush = $this->em->flush($visit)->will(function () { + $flush = $this->em->flush()->will(function () { }); $resolveIp = $this->ipLocationResolver->resolveIpLocation(Argument::any()); + $dispatch = $this->eventDispatcher->dispatch(new VisitLocated('123'))->will(function () { + }); ($this->locateVisit)($event); @@ -108,6 +124,7 @@ class LocateShortUrlVisitTest extends TestCase $flush->shouldHaveBeenCalledOnce(); $resolveIp->shouldNotHaveBeenCalled(); $this->logger->warning(Argument::cetera())->shouldNotHaveBeenCalled(); + $dispatch->shouldHaveBeenCalledOnce(); } public function provideNonLocatableVisits(): iterable @@ -128,9 +145,11 @@ class LocateShortUrlVisitTest extends TestCase $event = new ShortUrlVisited('123'); $findVisit = $this->em->find(Visit::class, '123')->willReturn($visit); - $flush = $this->em->flush($visit)->will(function () { + $flush = $this->em->flush()->will(function () { }); $resolveIp = $this->ipLocationResolver->resolveIpLocation($ipAddr)->willReturn($location); + $dispatch = $this->eventDispatcher->dispatch(new VisitLocated('123'))->will(function () { + }); ($this->locateVisit)($event); @@ -139,10 +158,11 @@ class LocateShortUrlVisitTest extends TestCase $flush->shouldHaveBeenCalledOnce(); $resolveIp->shouldHaveBeenCalledOnce(); $this->logger->warning(Argument::cetera())->shouldNotHaveBeenCalled(); + $dispatch->shouldHaveBeenCalledOnce(); } /** @test */ - public function errorWhenUpdatingGeoliteWithExistingCopyLogsWarning(): void + public function errorWhenUpdatingGeoLiteWithExistingCopyLogsWarning(): void { $e = GeolocationDbUpdateFailedException::create(true); $ipAddr = '1.2.3.0'; @@ -151,10 +171,12 @@ class LocateShortUrlVisitTest extends TestCase $event = new ShortUrlVisited('123'); $findVisit = $this->em->find(Visit::class, '123')->willReturn($visit); - $flush = $this->em->flush($visit)->will(function () { + $flush = $this->em->flush()->will(function () { }); $resolveIp = $this->ipLocationResolver->resolveIpLocation($ipAddr)->willReturn($location); $checkUpdateDb = $this->dbUpdater->checkDbUpdate(Argument::cetera())->willThrow($e); + $dispatch = $this->eventDispatcher->dispatch(new VisitLocated('123'))->will(function () { + }); ($this->locateVisit)($event); @@ -167,10 +189,11 @@ class LocateShortUrlVisitTest extends TestCase 'GeoLite2 database update failed. Proceeding with old version. {e}', ['e' => $e] )->shouldHaveBeenCalledOnce(); + $dispatch->shouldHaveBeenCalledOnce(); } /** @test */ - public function errorWhenDownloadingGeoliteCancelsLocation(): void + public function errorWhenDownloadingGeoLiteCancelsLocation(): void { $e = GeolocationDbUpdateFailedException::create(false); $ipAddr = '1.2.3.0'; @@ -179,14 +202,16 @@ class LocateShortUrlVisitTest extends TestCase $event = new ShortUrlVisited('123'); $findVisit = $this->em->find(Visit::class, '123')->willReturn($visit); - $flush = $this->em->flush($visit)->will(function () { + $flush = $this->em->flush()->will(function () { }); $resolveIp = $this->ipLocationResolver->resolveIpLocation($ipAddr)->willReturn($location); $checkUpdateDb = $this->dbUpdater->checkDbUpdate(Argument::cetera())->willThrow($e); $logError = $this->logger->error( - 'GeoLite2 database download failed. It is not possible to locate visit with id 123. {e}', - ['e' => $e] + 'GeoLite2 database download failed. It is not possible to locate visit with id {visitId}. {e}', + ['e' => $e, 'visitId' => 123] ); + $dispatch = $this->eventDispatcher->dispatch(new VisitLocated('123'))->will(function () { + }); ($this->locateVisit)($event); @@ -196,5 +221,6 @@ class LocateShortUrlVisitTest extends TestCase $resolveIp->shouldNotHaveBeenCalled(); $checkUpdateDb->shouldHaveBeenCalledOnce(); $logError->shouldHaveBeenCalledOnce(); + $dispatch->shouldHaveBeenCalledOnce(); } } diff --git a/module/Core/test/Exception/DeleteShortUrlExceptionTest.php b/module/Core/test/Exception/DeleteShortUrlExceptionTest.php index 4b132eea..f2207c54 100644 --- a/module/Core/test/Exception/DeleteShortUrlExceptionTest.php +++ b/module/Core/test/Exception/DeleteShortUrlExceptionTest.php @@ -5,17 +5,15 @@ declare(strict_types=1); namespace ShlinkioTest\Shlink\Core\Exception; use PHPUnit\Framework\TestCase; -use Shlinkio\Shlink\Common\Util\StringUtilsTrait; use Shlinkio\Shlink\Core\Exception\DeleteShortUrlException; use function Functional\map; use function range; +use function Shlinkio\Shlink\Core\generateRandomShortCode; use function sprintf; class DeleteShortUrlExceptionTest extends TestCase { - use StringUtilsTrait; - /** * @test * @dataProvider provideThresholds @@ -29,29 +27,20 @@ class DeleteShortUrlExceptionTest extends TestCase $this->assertEquals($threshold, $e->getVisitsThreshold()); $this->assertEquals($expectedMessage, $e->getMessage()); - $this->assertEquals(0, $e->getCode()); - $this->assertNull($e->getPrevious()); - } - - /** - * @test - * @dataProvider provideThresholds - */ - public function visitsThresholdIsProperlyReturned(int $threshold): void - { - $e = new DeleteShortUrlException($threshold); - - $this->assertEquals($threshold, $e->getVisitsThreshold()); - $this->assertEquals('', $e->getMessage()); - $this->assertEquals(0, $e->getCode()); - $this->assertNull($e->getPrevious()); + $this->assertEquals($expectedMessage, $e->getDetail()); + $this->assertEquals([ + 'shortCode' => $shortCode, + 'threshold' => $threshold, + ], $e->getAdditionalData()); + $this->assertEquals('Cannot delete short URL', $e->getTitle()); + $this->assertEquals('INVALID_SHORTCODE_DELETION', $e->getType()); + $this->assertEquals(422, $e->getStatus()); } public function provideThresholds(): array { return map(range(5, 50, 5), function (int $number) { - $shortCode = $this->generateRandomString(6); - return [$number, $shortCode, sprintf( + return [$number, $shortCode = generateRandomShortCode(6), sprintf( 'Impossible to delete short URL with short code "%s" since it has more than "%s" visits.', $shortCode, $number diff --git a/module/Core/test/Exception/InvalidShortCodeExceptionTest.php b/module/Core/test/Exception/InvalidShortCodeExceptionTest.php deleted file mode 100644 index 02a3edf2..00000000 --- a/module/Core/test/Exception/InvalidShortCodeExceptionTest.php +++ /dev/null @@ -1,40 +0,0 @@ -assertEquals('Provided short code "abc123" does not match the char set "def456"', $e->getMessage()); - $this->assertEquals($prev !== null ? $prev->getCode() : -1, $e->getCode()); - $this->assertEquals($prev, $e->getPrevious()); - } - - public function providePrevious(): iterable - { - yield 'null previous' => [null]; - yield 'instance previous' => [new Exception('Previous error', 10)]; - } - - /** @test */ - public function properlyCreatesExceptionFromNotFoundShortCode(): void - { - $e = InvalidShortCodeException::fromNotFoundShortCode('abc123'); - - $this->assertEquals('Provided short code "abc123" does not belong to a short URL', $e->getMessage()); - } -} diff --git a/module/Core/test/Exception/InvalidUrlExceptionTest.php b/module/Core/test/Exception/InvalidUrlExceptionTest.php index a5d19341..cb0a08bc 100644 --- a/module/Core/test/Exception/InvalidUrlExceptionTest.php +++ b/module/Core/test/Exception/InvalidUrlExceptionTest.php @@ -5,10 +5,13 @@ declare(strict_types=1); namespace ShlinkioTest\Shlink\Core\Exception; use Exception; +use Fig\Http\Message\StatusCodeInterface; use PHPUnit\Framework\TestCase; use Shlinkio\Shlink\Core\Exception\InvalidUrlException; use Throwable; +use function sprintf; + class InvalidUrlExceptionTest extends TestCase { /** @@ -17,10 +20,17 @@ class InvalidUrlExceptionTest extends TestCase */ public function properlyCreatesExceptionFromUrl(?Throwable $prev): void { - $e = InvalidUrlException::fromUrl('http://the_url.com', $prev); + $url = 'http://the_url.com'; + $expectedMessage = sprintf('Provided URL %s is invalid. Try with a different one.', $url); + $e = InvalidUrlException::fromUrl($url, $prev); - $this->assertEquals('Provided URL "http://the_url.com" is not an existing and valid URL', $e->getMessage()); - $this->assertEquals($prev !== null ? $prev->getCode() : -1, $e->getCode()); + $this->assertEquals($expectedMessage, $e->getMessage()); + $this->assertEquals($expectedMessage, $e->getDetail()); + $this->assertEquals('Invalid URL', $e->getTitle()); + $this->assertEquals('INVALID_URL', $e->getType()); + $this->assertEquals(['url' => $url], $e->getAdditionalData()); + $this->assertEquals(StatusCodeInterface::STATUS_BAD_REQUEST, $e->getCode()); + $this->assertEquals(StatusCodeInterface::STATUS_BAD_REQUEST, $e->getStatus()); $this->assertEquals($prev, $e->getPrevious()); } diff --git a/module/Core/test/Exception/NonUniqueSlugExceptionTest.php b/module/Core/test/Exception/NonUniqueSlugExceptionTest.php index 71c4a276..00efa3cf 100644 --- a/module/Core/test/Exception/NonUniqueSlugExceptionTest.php +++ b/module/Core/test/Exception/NonUniqueSlugExceptionTest.php @@ -15,19 +15,30 @@ class NonUniqueSlugExceptionTest extends TestCase */ public function properlyCreatesExceptionFromSlug(string $expectedMessage, string $slug, ?string $domain): void { + $expectedAdditional = ['customSlug' => $slug]; + if ($domain !== null) { + $expectedAdditional['domain'] = $domain; + } + $e = NonUniqueSlugException::fromSlug($slug, $domain); + $this->assertEquals($expectedMessage, $e->getMessage()); + $this->assertEquals($expectedMessage, $e->getDetail()); + $this->assertEquals('Invalid custom slug', $e->getTitle()); + $this->assertEquals('INVALID_SLUG', $e->getType()); + $this->assertEquals(400, $e->getStatus()); + $this->assertEquals($expectedAdditional, $e->getAdditionalData()); } public function provideMessages(): iterable { yield 'without domain' => [ - 'Provided slug "foo" is not unique.', + 'Provided slug "foo" is already in use.', 'foo', null, ]; yield 'with domain' => [ - 'Provided slug "baz" is not unique for domain "bar".', + 'Provided slug "baz" is already in use for domain "bar".', 'baz', 'bar', ]; diff --git a/module/Core/test/Exception/ShortUrlNotFoundExceptionTest.php b/module/Core/test/Exception/ShortUrlNotFoundExceptionTest.php new file mode 100644 index 00000000..be02a66c --- /dev/null +++ b/module/Core/test/Exception/ShortUrlNotFoundExceptionTest.php @@ -0,0 +1,49 @@ + $shortCode]; + if ($domain !== null) { + $expectedAdditional['domain'] = $domain; + } + + $e = ShortUrlNotFoundException::fromNotFoundShortCode($shortCode, $domain); + + $this->assertEquals($expectedMessage, $e->getMessage()); + $this->assertEquals($expectedMessage, $e->getDetail()); + $this->assertEquals('Short URL not found', $e->getTitle()); + $this->assertEquals('INVALID_SHORTCODE', $e->getType()); + $this->assertEquals(404, $e->getStatus()); + $this->assertEquals($expectedAdditional, $e->getAdditionalData()); + } + + public function provideMessages(): iterable + { + yield 'without domain' => [ + 'No URL found with short code "abc123"', + 'abc123', + null, + ]; + yield 'with domain' => [ + 'No URL found with short code "bar" for domain "foo"', + 'bar', + 'foo', + ]; + } +} diff --git a/module/Core/test/Exception/TagConflictExceptionTest.php b/module/Core/test/Exception/TagConflictExceptionTest.php new file mode 100644 index 00000000..f09e3a32 --- /dev/null +++ b/module/Core/test/Exception/TagConflictExceptionTest.php @@ -0,0 +1,29 @@ +assertEquals($expectedMessage, $e->getMessage()); + $this->assertEquals($expectedMessage, $e->getDetail()); + $this->assertEquals('Tag conflict', $e->getTitle()); + $this->assertEquals('TAG_CONFLICT', $e->getType()); + $this->assertEquals(['oldName' => $oldName, 'newName' => $newName], $e->getAdditionalData()); + $this->assertEquals(409, $e->getStatus()); + } +} diff --git a/module/Core/test/Exception/TagNotFoundExceptionTest.php b/module/Core/test/Exception/TagNotFoundExceptionTest.php new file mode 100644 index 00000000..ccee7b38 --- /dev/null +++ b/module/Core/test/Exception/TagNotFoundExceptionTest.php @@ -0,0 +1,28 @@ +assertEquals($expectedMessage, $e->getMessage()); + $this->assertEquals($expectedMessage, $e->getDetail()); + $this->assertEquals('Tag not found', $e->getTitle()); + $this->assertEquals('TAG_NOT_FOUND', $e->getType()); + $this->assertEquals(['tag' => $tag], $e->getAdditionalData()); + $this->assertEquals(404, $e->getStatus()); + } +} diff --git a/module/Core/test/Exception/ValidationExceptionTest.php b/module/Core/test/Exception/ValidationExceptionTest.php index 5cab422c..11bb8026 100644 --- a/module/Core/test/Exception/ValidationExceptionTest.php +++ b/module/Core/test/Exception/ValidationExceptionTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace ShlinkioTest\Shlink\Core\Exception; +use Fig\Http\Message\StatusCodeInterface; use LogicException; use PHPUnit\Framework\TestCase; use RuntimeException; @@ -11,39 +12,11 @@ use Shlinkio\Shlink\Core\Exception\ValidationException; use Throwable; use Zend\InputFilter\InputFilterInterface; +use function array_keys; use function print_r; -use function random_int; class ValidationExceptionTest extends TestCase { - /** - * @test - * @dataProvider provideExceptionData - */ - public function createsExceptionWrappingExpectedData( - array $args, - string $expectedMessage, - array $expectedInvalidElements, - int $expectedCode, - ?Throwable $expectedPrev - ): void { - $e = new ValidationException(...$args); - - $this->assertEquals($expectedMessage, $e->getMessage()); - $this->assertEquals($expectedInvalidElements, $e->getInvalidElements()); - $this->assertEquals($expectedCode, $e->getCode()); - $this->assertEquals($expectedPrev, $e->getPrevious()); - } - - public function provideExceptionData(): iterable - { - yield 'empty args' => [[], '', [], 0, null]; - yield 'with message' => [['something'], 'something', [], 0, null]; - yield 'with elements' => [['something_else', [1, 2, 3]], 'something_else', [1, 2, 3], 0, null]; - yield 'with code' => [['foo', [], $foo = random_int(-100, 100)], 'foo', [], $foo, null]; - yield 'with prev' => [['bar', [], 8, $e = new RuntimeException()], 'bar', [], 8, $e]; - } - /** * @test * @dataProvider provideExceptions @@ -55,12 +28,9 @@ class ValidationExceptionTest extends TestCase 'something' => ['baz', 'foo'], ]; $barValue = print_r(['baz', 'foo'], true); - $expectedMessage = << bar 'something' => {$barValue} - EOT; $inputFilter = $this->prophesize(InputFilterInterface::class); @@ -69,9 +39,11 @@ EOT; $e = ValidationException::fromInputFilter($inputFilter->reveal()); $this->assertEquals($invalidData, $e->getInvalidElements()); - $this->assertEquals($expectedMessage, $e->getMessage()); - $this->assertEquals(-1, $e->getCode()); + $this->assertEquals(['invalidElements' => array_keys($invalidData)], $e->getAdditionalData()); + $this->assertEquals('Provided data is not valid', $e->getMessage()); + $this->assertEquals(StatusCodeInterface::STATUS_BAD_REQUEST, $e->getCode()); $this->assertEquals($prev, $e->getPrevious()); + $this->assertStringContainsString($expectedStringRepresentation, (string) $e); $getMessages->shouldHaveBeenCalledOnce(); } diff --git a/module/Core/test/Paginator/Adapter/ShortUrlRepositoryAdapterTest.php b/module/Core/test/Paginator/Adapter/ShortUrlRepositoryAdapterTest.php index a7229147..8bf69faf 100644 --- a/module/Core/test/Paginator/Adapter/ShortUrlRepositoryAdapterTest.php +++ b/module/Core/test/Paginator/Adapter/ShortUrlRepositoryAdapterTest.php @@ -4,35 +4,63 @@ declare(strict_types=1); namespace ShlinkioTest\Shlink\Core\Paginator\Adapter; +use Cake\Chronos\Chronos; use PHPUnit\Framework\TestCase; use Prophecy\Prophecy\ObjectProphecy; +use Shlinkio\Shlink\Common\Util\DateRange; use Shlinkio\Shlink\Core\Paginator\Adapter\ShortUrlRepositoryAdapter; use Shlinkio\Shlink\Core\Repository\ShortUrlRepositoryInterface; class ShortUrlRepositoryAdapterTest extends TestCase { - /** @var ShortUrlRepositoryAdapter */ - private $adapter; /** @var ObjectProphecy */ private $repo; public function setUp(): void { $this->repo = $this->prophesize(ShortUrlRepositoryInterface::class); - $this->adapter = new ShortUrlRepositoryAdapter($this->repo->reveal(), 'search', ['foo', 'bar'], 'order'); } - /** @test */ - public function getItemsFallbacksToFindList(): void - { - $this->repo->findList(10, 5, 'search', ['foo', 'bar'], 'order')->shouldBeCalledOnce(); - $this->adapter->getItems(5, 10); + /** + * @test + * @dataProvider provideFilteringArgs + */ + public function getItemsFallsBackToFindList( + $searchTerm = null, + array $tags = [], + ?DateRange $dateRange = null, + $orderBy = null + ): void { + $adapter = new ShortUrlRepositoryAdapter($this->repo->reveal(), $searchTerm, $tags, $orderBy, $dateRange); + + $this->repo->findList(10, 5, $searchTerm, $tags, $orderBy, $dateRange)->shouldBeCalledOnce(); + $adapter->getItems(5, 10); } - /** @test */ - public function countFallbacksToCountList(): void + /** + * @test + * @dataProvider provideFilteringArgs + */ + public function countFallsBackToCountList($searchTerm = null, array $tags = [], ?DateRange $dateRange = null): void { - $this->repo->countList('search', ['foo', 'bar'])->shouldBeCalledOnce(); - $this->adapter->count(); + $adapter = new ShortUrlRepositoryAdapter($this->repo->reveal(), $searchTerm, $tags, null, $dateRange); + + $this->repo->countList($searchTerm, $tags, $dateRange)->shouldBeCalledOnce(); + $adapter->count(); + } + + public function provideFilteringArgs(): iterable + { + yield []; + yield ['search']; + yield ['search', []]; + yield ['search', ['foo', 'bar']]; + yield ['search', ['foo', 'bar'], null, 'order']; + yield ['search', ['foo', 'bar'], new DateRange(), 'order']; + yield ['search', ['foo', 'bar'], new DateRange(Chronos::now()), 'order']; + yield ['search', ['foo', 'bar'], new DateRange(null, Chronos::now()), 'order']; + yield ['search', ['foo', 'bar'], new DateRange(Chronos::now(), Chronos::now()), 'order']; + yield ['search', ['foo', 'bar'], new DateRange(Chronos::now())]; + yield [null, ['foo', 'bar'], new DateRange(Chronos::now(), Chronos::now())]; } } diff --git a/module/Core/test/Response/NotFoundHandlerTest.php b/module/Core/test/Response/NotFoundHandlerTest.php deleted file mode 100644 index 8f1d6f51..00000000 --- a/module/Core/test/Response/NotFoundHandlerTest.php +++ /dev/null @@ -1,142 +0,0 @@ -renderer = $this->prophesize(TemplateRendererInterface::class); - $this->redirectOptions = new NotFoundRedirectOptions(); - - $this->delegate = new NotFoundHandler($this->renderer->reveal(), $this->redirectOptions, ''); - } - - /** - * @test - * @dataProvider provideResponses - */ - public function properResponseTypeIsReturned(string $expectedResponse, string $accept, int $renderCalls): void - { - $request = (new ServerRequest())->withHeader('Accept', $accept); - $render = $this->renderer->render(Argument::cetera())->willReturn(''); - - $resp = $this->delegate->handle($request); - - $this->assertInstanceOf($expectedResponse, $resp); - $render->shouldHaveBeenCalledTimes($renderCalls); - } - - public function provideResponses(): iterable - { - yield 'application/json' => [Response\JsonResponse::class, 'application/json', 0]; - yield 'text/json' => [Response\JsonResponse::class, 'text/json', 0]; - yield 'application/x-json' => [Response\JsonResponse::class, 'application/x-json', 0]; - yield 'text/html' => [Response\HtmlResponse::class, 'text/html', 1]; - } - - /** - * @test - * @dataProvider provideRedirects - */ - public function expectedRedirectionIsReturnedDependingOnTheCase( - ServerRequestInterface $request, - string $expectedRedirectTo - ): void { - $this->redirectOptions->invalidShortUrl = 'invalidShortUrl'; - $this->redirectOptions->regular404 = 'regular404'; - $this->redirectOptions->baseUrl = 'baseUrl'; - - $resp = $this->delegate->handle($request); - - $this->assertInstanceOf(Response\RedirectResponse::class, $resp); - $this->assertEquals($expectedRedirectTo, $resp->getHeaderLine('Location')); - $this->renderer->render(Argument::cetera())->shouldNotHaveBeenCalled(); - } - - public function provideRedirects(): iterable - { - yield 'base URL with trailing slash' => [ - ServerRequestFactory::fromGlobals()->withUri(new Uri('/')), - 'baseUrl', - ]; - yield 'base URL without trailing slash' => [ - ServerRequestFactory::fromGlobals()->withUri(new Uri('')), - 'baseUrl', - ]; - yield 'regular 404' => [ - ServerRequestFactory::fromGlobals()->withUri(new Uri('/foo/bar')), - 'regular404', - ]; - yield 'invalid short URL' => [ - ServerRequestFactory::fromGlobals() - ->withAttribute( - RouteResult::class, - RouteResult::fromRoute( - new Route( - '', - $this->prophesize(MiddlewareInterface::class)->reveal(), - ['GET'], - RedirectAction::class - ) - ) - ) - ->withUri(new Uri('/abc123')), - 'invalidShortUrl', - ]; - } - - /** - * @test - * @dataProvider provideTemplates - */ - public function properErrorTemplateIsRendered(ServerRequestInterface $request, string $expectedTemplate): void - { - $request = $request->withHeader('Accept', 'text/html'); - $render = $this->renderer->render($expectedTemplate)->willReturn(''); - - $resp = $this->delegate->handle($request); - - $this->assertInstanceOf(Response\HtmlResponse::class, $resp); - $render->shouldHaveBeenCalledOnce(); - } - - public function provideTemplates(): iterable - { - $request = ServerRequestFactory::fromGlobals(); - - yield [$request, NotFoundHandler::NOT_FOUND_TEMPLATE]; - yield [ - $request->withAttribute( - RouteResult::class, - RouteResult::fromRoute(new Route('', $this->prophesize(MiddlewareInterface::class)->reveal())) - ), - NotFoundHandler::INVALID_SHORT_CODE_TEMPLATE, - ]; - } -} diff --git a/module/Core/test/Service/ShortUrlServiceTest.php b/module/Core/test/Service/ShortUrlServiceTest.php index 9fd19394..3dae00a7 100644 --- a/module/Core/test/Service/ShortUrlServiceTest.php +++ b/module/Core/test/Service/ShortUrlServiceTest.php @@ -12,7 +12,7 @@ use Prophecy\Argument; use Prophecy\Prophecy\ObjectProphecy; use Shlinkio\Shlink\Core\Entity\ShortUrl; use Shlinkio\Shlink\Core\Entity\Tag; -use Shlinkio\Shlink\Core\Exception\InvalidShortCodeException; +use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException; use Shlinkio\Shlink\Core\Model\ShortUrlMeta; use Shlinkio\Shlink\Core\Repository\ShortUrlRepository; use Shlinkio\Shlink\Core\Service\ShortUrlService; @@ -35,7 +35,7 @@ class ShortUrlServiceTest extends TestCase } /** @test */ - public function listedUrlsAreReturnedFromEntityManager() + public function listedUrlsAreReturnedFromEntityManager(): void { $list = [ new ShortUrl(''), @@ -54,7 +54,7 @@ class ShortUrlServiceTest extends TestCase } /** @test */ - public function exceptionIsThrownWhenSettingTagsOnInvalidShortcode() + public function exceptionIsThrownWhenSettingTagsOnInvalidShortcode(): void { $shortCode = 'abc123'; $repo = $this->prophesize(ShortUrlRepository::class); @@ -62,12 +62,12 @@ class ShortUrlServiceTest extends TestCase ->shouldBeCalledOnce(); $this->em->getRepository(ShortUrl::class)->willReturn($repo->reveal()); - $this->expectException(InvalidShortCodeException::class); + $this->expectException(ShortUrlNotFoundException::class); $this->service->setTagsByShortCode($shortCode); } /** @test */ - public function providedTagsAreGetFromRepoAndSetToTheShortUrl() + public function providedTagsAreGetFromRepoAndSetToTheShortUrl(): void { $shortUrl = $this->prophesize(ShortUrl::class); $shortUrl->setTags(Argument::any())->shouldBeCalledOnce(); @@ -86,14 +86,14 @@ class ShortUrlServiceTest extends TestCase } /** @test */ - public function updateMetadataByShortCodeUpdatesProvidedData() + public function updateMetadataByShortCodeUpdatesProvidedData(): void { $shortUrl = new ShortUrl(''); $repo = $this->prophesize(ShortUrlRepository::class); $findShortUrl = $repo->findOneBy(['shortCode' => 'abc123'])->willReturn($shortUrl); $getRepo = $this->em->getRepository(ShortUrl::class)->willReturn($repo->reveal()); - $flush = $this->em->flush($shortUrl)->willReturn(null); + $flush = $this->em->flush()->willReturn(null); $result = $this->service->updateMetadataByShortCode('abc123', ShortUrlMeta::createFromParams( Chronos::parse('2017-01-01 00:00:00')->toAtomString(), diff --git a/module/Core/test/Service/Tag/TagServiceTest.php b/module/Core/test/Service/Tag/TagServiceTest.php index 6b904fe5..d7e5b631 100644 --- a/module/Core/test/Service/Tag/TagServiceTest.php +++ b/module/Core/test/Service/Tag/TagServiceTest.php @@ -10,8 +10,8 @@ use PHPUnit\Framework\TestCase; use Prophecy\Argument; use Prophecy\Prophecy\ObjectProphecy; use Shlinkio\Shlink\Core\Entity\Tag; -use Shlinkio\Shlink\Core\Exception\EntityDoesNotExistException; use Shlinkio\Shlink\Core\Exception\TagConflictException; +use Shlinkio\Shlink\Core\Exception\TagNotFoundException; use Shlinkio\Shlink\Core\Repository\TagRepository; use Shlinkio\Shlink\Core\Service\Tag\TagService; @@ -29,7 +29,7 @@ class TagServiceTest extends TestCase } /** @test */ - public function listTagsDelegatesOnRepository() + public function listTagsDelegatesOnRepository(): void { $expected = [new Tag('foo'), new Tag('bar')]; @@ -45,7 +45,7 @@ class TagServiceTest extends TestCase } /** @test */ - public function deleteTagsDelegatesOnRepository() + public function deleteTagsDelegatesOnRepository(): void { $repo = $this->prophesize(TagRepository::class); $delete = $repo->deleteByName(['foo', 'bar'])->willReturn(4); @@ -58,7 +58,7 @@ class TagServiceTest extends TestCase } /** @test */ - public function createTagsPersistsEntities() + public function createTagsPersistsEntities(): void { $repo = $this->prophesize(TagRepository::class); $find = $repo->findOneBy(Argument::cetera())->willReturn(new Tag('foo')); @@ -76,7 +76,7 @@ class TagServiceTest extends TestCase } /** @test */ - public function renameInvalidTagThrowsException() + public function renameInvalidTagThrowsException(): void { $repo = $this->prophesize(TagRepository::class); $find = $repo->findOneBy(Argument::cetera())->willReturn(null); @@ -84,7 +84,7 @@ class TagServiceTest extends TestCase $find->shouldBeCalled(); $getRepo->shouldBeCalled(); - $this->expectException(EntityDoesNotExistException::class); + $this->expectException(TagNotFoundException::class); $this->service->renameTag('foo', 'bar'); } @@ -101,7 +101,7 @@ class TagServiceTest extends TestCase $find = $repo->findOneBy(Argument::cetera())->willReturn($expected); $countTags = $repo->count(Argument::cetera())->willReturn($count); $getRepo = $this->em->getRepository(Tag::class)->willReturn($repo->reveal()); - $flush = $this->em->flush($expected)->willReturn(null); + $flush = $this->em->flush()->willReturn(null); $tag = $this->service->renameTag($oldName, $newName); diff --git a/module/Core/test/Service/VisitsTrackerTest.php b/module/Core/test/Service/VisitsTrackerTest.php index f137fd54..a59429fb 100644 --- a/module/Core/test/Service/VisitsTrackerTest.php +++ b/module/Core/test/Service/VisitsTrackerTest.php @@ -46,11 +46,11 @@ class VisitsTrackerTest extends TestCase $repo->findOneBy(['shortCode' => $shortCode])->willReturn(new ShortUrl('')); $this->em->getRepository(ShortUrl::class)->willReturn($repo->reveal())->shouldBeCalledOnce(); - $this->em->persist(Argument::any())->shouldBeCalledOnce(); - $this->em->flush(Argument::that(function (Visit $visit) { + $this->em->persist(Argument::that(function (Visit $visit) { $visit->setId('1'); return $visit; }))->shouldBeCalledOnce(); + $this->em->flush()->shouldBeCalledOnce(); $this->visitsTracker->track($shortCode, Visitor::emptyInstance()); @@ -69,11 +69,10 @@ class VisitsTrackerTest extends TestCase /** @var Visit $visit */ $visit = $args[0]; Assert::assertEquals('4.3.2.0', $visit->getRemoteAddr()); - })->shouldBeCalledOnce(); - $this->em->flush(Argument::that(function (Visit $visit) { $visit->setId('1'); return $visit; - }))->shouldBeCalledOnce(); + })->shouldBeCalledOnce(); + $this->em->flush()->shouldBeCalledOnce(); $this->visitsTracker->track($shortCode, new Visitor('', '', '4.3.2.1')); diff --git a/module/Core/test/Util/UrlValidatorTest.php b/module/Core/test/Util/UrlValidatorTest.php index 5dbfe582..3a6880ea 100644 --- a/module/Core/test/Util/UrlValidatorTest.php +++ b/module/Core/test/Util/UrlValidatorTest.php @@ -7,17 +7,14 @@ namespace ShlinkioTest\Shlink\Core\Util; use Fig\Http\Message\RequestMethodInterface; use GuzzleHttp\ClientInterface; use GuzzleHttp\Exception\ClientException; +use GuzzleHttp\RequestOptions; use PHPUnit\Framework\TestCase; use Prophecy\Argument; use Prophecy\Prophecy\ObjectProphecy; use Shlinkio\Shlink\Core\Exception\InvalidUrlException; use Shlinkio\Shlink\Core\Util\UrlValidator; -use Zend\Diactoros\Request; use Zend\Diactoros\Response; -use function Functional\map; -use function range; - class UrlValidatorTest extends TestCase { /** @var UrlValidator */ @@ -31,71 +28,30 @@ class UrlValidatorTest extends TestCase $this->urlValidator = new UrlValidator($this->httpClient->reveal()); } - /** - * @test - * @dataProvider provideAttemptThatThrows - */ - public function exceptionIsThrownWhenUrlIsInvalid(int $attemptThatThrows): void + /** @test */ + public function exceptionIsThrownWhenUrlIsInvalid(): void { - $callNum = 1; - $e = new ClientException('', $this->prophesize(Request::class)->reveal()); + $request = $this->httpClient->request(Argument::cetera())->willThrow(ClientException::class); - $request = $this->httpClient->request(Argument::cetera())->will( - function () use ($e, $attemptThatThrows, &$callNum) { - if ($callNum === $attemptThatThrows) { - throw $e; - } - - $callNum++; - return new Response('php://memory', 302, ['Location' => 'http://foo.com']); - } - ); - - $request->shouldBeCalledTimes($attemptThatThrows); + $request->shouldBeCalledOnce(); $this->expectException(InvalidUrlException::class); $this->urlValidator->validateUrl('http://foobar.com/12345/hello?foo=bar'); } - public function provideAttemptThatThrows(): iterable + /** @test */ + public function expectedUrlIsCalledWhenTryingToVerify(): void { - return map(range(1, 15), function (int $attempt) { - return [$attempt]; - }); - } + $expectedUrl = 'http://foobar.com'; - /** - * @test - * @dataProvider provideUrls - */ - public function expectedUrlIsCalledInOrderToVerifyProvidedUrl(string $providedUrl, string $expectedUrl): void - { $request = $this->httpClient->request( RequestMethodInterface::METHOD_GET, $expectedUrl, - Argument::cetera() + [RequestOptions::ALLOW_REDIRECTS => ['max' => 15]] )->willReturn(new Response()); - $this->urlValidator->validateUrl($providedUrl); + $this->urlValidator->validateUrl($expectedUrl); $request->shouldHaveBeenCalledOnce(); } - - public function provideUrls(): iterable - { - yield 'regular domain' => ['http://foobar.com', 'http://foobar.com']; - yield 'IDN' => ['https://tést.shlink.io', 'https://xn--tst-bma.shlink.io']; - } - - /** @test */ - public function considersUrlValidWhenTooManyRedirectsAreReturned(): void - { - $request = $this->httpClient->request(Argument::cetera())->willReturn( - new Response('php://memory', 302, ['Location' => 'http://foo.com']) - ); - - $this->urlValidator->validateUrl('http://foobar.com'); - - $request->shouldHaveBeenCalledTimes(15); - } } diff --git a/module/Rest/config/auth.config.php b/module/Rest/config/auth.config.php index 7acb133e..9d0987e0 100644 --- a/module/Rest/config/auth.config.php +++ b/module/Rest/config/auth.config.php @@ -48,7 +48,6 @@ return [ Middleware\AuthenticationMiddleware::class => [ Authentication\RequestToHttpAuthPlugin::class, 'config.auth.routes_whitelist', - 'Logger_Shlink', ], ], diff --git a/module/Rest/config/dependencies.config.php b/module/Rest/config/dependencies.config.php index 54f380b3..17c30642 100644 --- a/module/Rest/config/dependencies.config.php +++ b/module/Rest/config/dependencies.config.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Shlinkio\Shlink\Rest; +use Doctrine\DBAL\Connection; use Psr\Log\LoggerInterface; use Shlinkio\Shlink\Core\Options\AppOptions; use Shlinkio\Shlink\Core\Service; @@ -20,15 +21,15 @@ return [ ApiKeyService::class => ConfigAbstractFactory::class, Action\AuthenticateAction::class => ConfigAbstractFactory::class, - Action\HealthAction::class => Action\HealthActionFactory::class, + Action\HealthAction::class => ConfigAbstractFactory::class, Action\ShortUrl\CreateShortUrlAction::class => ConfigAbstractFactory::class, Action\ShortUrl\SingleStepCreateShortUrlAction::class => ConfigAbstractFactory::class, Action\ShortUrl\EditShortUrlAction::class => ConfigAbstractFactory::class, Action\ShortUrl\DeleteShortUrlAction::class => ConfigAbstractFactory::class, Action\ShortUrl\ResolveShortUrlAction::class => ConfigAbstractFactory::class, - Action\Visit\GetVisitsAction::class => ConfigAbstractFactory::class, Action\ShortUrl\ListShortUrlsAction::class => ConfigAbstractFactory::class, Action\ShortUrl\EditShortUrlTagsAction::class => ConfigAbstractFactory::class, + Action\Visit\GetVisitsAction::class => ConfigAbstractFactory::class, Action\Tag\ListTagsAction::class => ConfigAbstractFactory::class, Action\Tag\DeleteTagsAction::class => ConfigAbstractFactory::class, Action\Tag\CreateTagsAction::class => ConfigAbstractFactory::class, @@ -38,6 +39,7 @@ return [ Middleware\BodyParserMiddleware::class => InvokableFactory::class, Middleware\CrossDomainMiddleware::class => InvokableFactory::class, Middleware\PathVersionMiddleware::class => InvokableFactory::class, + Middleware\BackwardsCompatibleProblemDetailsMiddleware::class => ConfigAbstractFactory::class, Middleware\ShortUrl\CreateShortUrlContentNegotiationMiddleware::class => InvokableFactory::class, Middleware\ShortUrl\ShortCodePathMiddleware::class => InvokableFactory::class, ], @@ -48,6 +50,7 @@ return [ ApiKeyService::class => ['em'], Action\AuthenticateAction::class => [ApiKeyService::class, Authentication\JWTService::class, 'Logger_Shlink'], + Action\HealthAction::class => [Connection::class, AppOptions::class, 'Logger_Shlink'], Action\ShortUrl\CreateShortUrlAction::class => [ Service\UrlShortener::class, 'config.url_shortener.domain', @@ -73,6 +76,11 @@ return [ 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, LoggerInterface::class], + + Middleware\BackwardsCompatibleProblemDetailsMiddleware::class => [ + 'config.backwards_compatible_problem_details.default_type_fallbacks', + 'config.backwards_compatible_problem_details.json_flags', + ], ], ]; diff --git a/module/Rest/config/error-handler.config.php b/module/Rest/config/error-handler.config.php deleted file mode 100644 index c7503b72..00000000 --- a/module/Rest/config/error-handler.config.php +++ /dev/null @@ -1,21 +0,0 @@ - [ - 'plugins' => [ - 'invokables' => [ - 'application/json' => JsonErrorResponseGenerator::class, - ], - 'aliases' => [ - 'application/x-json' => 'application/json', - 'text/json' => 'application/json', - ], - ], - ], - -]; diff --git a/module/Rest/src/Action/AuthenticateAction.php b/module/Rest/src/Action/AuthenticateAction.php index 1476f6de..b0919aae 100644 --- a/module/Rest/src/Action/AuthenticateAction.php +++ b/module/Rest/src/Action/AuthenticateAction.php @@ -10,7 +10,6 @@ use Psr\Log\LoggerInterface; use Shlinkio\Shlink\Rest\Authentication\JWTServiceInterface; use Shlinkio\Shlink\Rest\Service\ApiKeyService; use Shlinkio\Shlink\Rest\Service\ApiKeyServiceInterface; -use Shlinkio\Shlink\Rest\Util\RestUtils; use Zend\Diactoros\Response\JsonResponse; /** @deprecated */ @@ -44,7 +43,7 @@ class AuthenticateAction extends AbstractRestAction $authData = $request->getParsedBody(); if (! isset($authData['apiKey'])) { return new JsonResponse([ - 'error' => RestUtils::INVALID_ARGUMENT_ERROR, + 'error' => 'INVALID_ARGUMENT', 'message' => 'You have to provide a valid API key under the "apiKey" param name.', ], self::STATUS_BAD_REQUEST); } @@ -53,7 +52,7 @@ class AuthenticateAction extends AbstractRestAction $apiKey = $this->apiKeyService->getByKey($authData['apiKey']); if ($apiKey === null || ! $apiKey->isValid()) { return new JsonResponse([ - 'error' => RestUtils::INVALID_API_KEY_ERROR, + 'error' => 'INVALID_API_KEY', 'message' => 'Provided API key does not exist or is invalid.', ], self::STATUS_UNAUTHORIZED); } diff --git a/module/Rest/src/Action/HealthAction.php b/module/Rest/src/Action/HealthAction.php index 23090165..ac548fde 100644 --- a/module/Rest/src/Action/HealthAction.php +++ b/module/Rest/src/Action/HealthAction.php @@ -15,8 +15,8 @@ use Zend\Diactoros\Response\JsonResponse; class HealthAction extends AbstractRestAction { private const HEALTH_CONTENT_TYPE = 'application/health+json'; - private const PASS_STATUS = 'pass'; - private const FAIL_STATUS = 'fail'; + private const STATUS_PASS = 'pass'; + private const STATUS_FAIL = 'fail'; protected const ROUTE_PATH = '/health'; protected const ROUTE_ALLOWED_METHODS = [self::METHOD_GET]; @@ -48,7 +48,7 @@ class HealthAction extends AbstractRestAction $statusCode = $connected ? self::STATUS_OK : self::STATUS_SERVICE_UNAVAILABLE; return new JsonResponse([ - 'status' => $connected ? self::PASS_STATUS : self::FAIL_STATUS, + 'status' => $connected ? self::STATUS_PASS : self::STATUS_FAIL, 'version' => $this->options->getVersion(), 'links' => [ 'about' => 'https://shlink.io', diff --git a/module/Rest/src/Action/HealthActionFactory.php b/module/Rest/src/Action/HealthActionFactory.php deleted file mode 100644 index 269a8f4d..00000000 --- a/module/Rest/src/Action/HealthActionFactory.php +++ /dev/null @@ -1,20 +0,0 @@ -get(EntityManager::class); - $options = $container->get(AppOptions::class); - $logger = $container->get('Logger_Shlink'); - return new HealthAction($em->getConnection(), $options, $logger); - } -} diff --git a/module/Rest/src/Action/ShortUrl/AbstractCreateShortUrlAction.php b/module/Rest/src/Action/ShortUrl/AbstractCreateShortUrlAction.php index e55f564e..af392067 100644 --- a/module/Rest/src/Action/ShortUrl/AbstractCreateShortUrlAction.php +++ b/module/Rest/src/Action/ShortUrl/AbstractCreateShortUrlAction.php @@ -7,19 +7,13 @@ namespace Shlinkio\Shlink\Rest\Action\ShortUrl; use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Log\LoggerInterface; -use Shlinkio\Shlink\Core\Exception\InvalidArgumentException; -use Shlinkio\Shlink\Core\Exception\InvalidUrlException; -use Shlinkio\Shlink\Core\Exception\NonUniqueSlugException; +use Shlinkio\Shlink\Core\Exception\ValidationException; use Shlinkio\Shlink\Core\Model\CreateShortUrlData; use Shlinkio\Shlink\Core\Service\UrlShortenerInterface; use Shlinkio\Shlink\Core\Transformer\ShortUrlDataTransformer; use Shlinkio\Shlink\Rest\Action\AbstractRestAction; -use Shlinkio\Shlink\Rest\Util\RestUtils; -use Throwable; use Zend\Diactoros\Response\JsonResponse; -use function sprintf; - abstract class AbstractCreateShortUrlAction extends AbstractRestAction { /** @var UrlShortenerInterface */ @@ -37,56 +31,23 @@ abstract class AbstractCreateShortUrlAction extends AbstractRestAction $this->domainConfig = $domainConfig; } - /** - * @param Request $request - * @return Response - */ public function handle(Request $request): Response { - try { - $shortUrlData = $this->buildShortUrlData($request); - } catch (InvalidArgumentException $e) { - $this->logger->warning('Provided data is invalid. {e}', ['e' => $e]); - return new JsonResponse([ - 'error' => RestUtils::INVALID_ARGUMENT_ERROR, - 'message' => $e->getMessage(), - ], self::STATUS_BAD_REQUEST); - } - + $shortUrlData = $this->buildShortUrlData($request); $longUrl = $shortUrlData->getLongUrl(); + $tags = $shortUrlData->getTags(); $shortUrlMeta = $shortUrlData->getMeta(); - try { - $shortUrl = $this->urlShortener->urlToShortCode($longUrl, $shortUrlData->getTags(), $shortUrlMeta); - $transformer = new ShortUrlDataTransformer($this->domainConfig); + $shortUrl = $this->urlShortener->urlToShortCode($longUrl, $tags, $shortUrlMeta); + $transformer = new ShortUrlDataTransformer($this->domainConfig); - return new JsonResponse($transformer->transform($shortUrl)); - } catch (InvalidUrlException $e) { - $this->logger->warning('Provided Invalid URL. {e}', ['e' => $e]); - return new JsonResponse([ - 'error' => RestUtils::getRestErrorCodeFromException($e), - 'message' => sprintf('Provided URL %s is invalid. Try with a different one.', $longUrl), - ], self::STATUS_BAD_REQUEST); - } catch (NonUniqueSlugException $e) { - $customSlug = $shortUrlMeta->getCustomSlug(); - $this->logger->warning('Provided non-unique slug. {e}', ['e' => $e]); - return new JsonResponse([ - 'error' => RestUtils::getRestErrorCodeFromException($e), - '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' => 'Unexpected error occurred', - ], self::STATUS_INTERNAL_SERVER_ERROR); - } + return new JsonResponse($transformer->transform($shortUrl)); } /** * @param Request $request * @return CreateShortUrlData - * @throws InvalidArgumentException + * @throws ValidationException */ abstract protected function buildShortUrlData(Request $request): CreateShortUrlData; } diff --git a/module/Rest/src/Action/ShortUrl/CreateShortUrlAction.php b/module/Rest/src/Action/ShortUrl/CreateShortUrlAction.php index 96145ce0..e0b0ddac 100644 --- a/module/Rest/src/Action/ShortUrl/CreateShortUrlAction.php +++ b/module/Rest/src/Action/ShortUrl/CreateShortUrlAction.php @@ -5,7 +5,6 @@ declare(strict_types=1); namespace Shlinkio\Shlink\Rest\Action\ShortUrl; use Psr\Http\Message\ServerRequestInterface as Request; -use Shlinkio\Shlink\Core\Exception\InvalidArgumentException; use Shlinkio\Shlink\Core\Exception\ValidationException; use Shlinkio\Shlink\Core\Model\CreateShortUrlData; use Shlinkio\Shlink\Core\Model\ShortUrlMeta; @@ -19,29 +18,26 @@ class CreateShortUrlAction extends AbstractCreateShortUrlAction /** * @param Request $request * @return CreateShortUrlData - * @throws InvalidArgumentException - * @throws \InvalidArgumentException + * @throws ValidationException */ protected function buildShortUrlData(Request $request): CreateShortUrlData { $postData = (array) $request->getParsedBody(); if (! isset($postData['longUrl'])) { - throw new InvalidArgumentException('A URL was not provided'); + throw ValidationException::fromArray([ + 'longUrl' => 'A URL was not provided', + ]); } - try { - $meta = ShortUrlMeta::createFromParams( - $postData['validSince'] ?? null, - $postData['validUntil'] ?? null, - $postData['customSlug'] ?? null, - $postData['maxVisits'] ?? null, - $postData['findIfExists'] ?? null, - $postData['domain'] ?? null - ); + $meta = ShortUrlMeta::createFromParams( + $postData['validSince'] ?? null, + $postData['validUntil'] ?? null, + $postData['customSlug'] ?? null, + $postData['maxVisits'] ?? null, + $postData['findIfExists'] ?? null, + $postData['domain'] ?? null + ); - return new CreateShortUrlData(new Uri($postData['longUrl']), (array) ($postData['tags'] ?? []), $meta); - } catch (ValidationException $e) { - throw new InvalidArgumentException('Provided meta data is not valid', -1, $e); - } + return new CreateShortUrlData(new Uri($postData['longUrl']), (array) ($postData['tags'] ?? []), $meta); } } diff --git a/module/Rest/src/Action/ShortUrl/DeleteShortUrlAction.php b/module/Rest/src/Action/ShortUrl/DeleteShortUrlAction.php index 54755baa..ba39ec82 100644 --- a/module/Rest/src/Action/ShortUrl/DeleteShortUrlAction.php +++ b/module/Rest/src/Action/ShortUrl/DeleteShortUrlAction.php @@ -7,14 +7,9 @@ namespace Shlinkio\Shlink\Rest\Action\ShortUrl; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Log\LoggerInterface; -use Shlinkio\Shlink\Core\Exception; use Shlinkio\Shlink\Core\Service\ShortUrl\DeleteShortUrlServiceInterface; use Shlinkio\Shlink\Rest\Action\AbstractRestAction; -use Shlinkio\Shlink\Rest\Util\RestUtils; use Zend\Diactoros\Response\EmptyResponse; -use Zend\Diactoros\Response\JsonResponse; - -use function sprintf; class DeleteShortUrlAction extends AbstractRestAction { @@ -30,34 +25,10 @@ class DeleteShortUrlAction extends AbstractRestAction $this->deleteShortUrlService = $deleteShortUrlService; } - /** - * Handle the request and return a response. - */ public function handle(ServerRequestInterface $request): ResponseInterface { $shortCode = $request->getAttribute('shortCode', ''); - - try { - $this->deleteShortUrlService->deleteByShortCode($shortCode); - return new EmptyResponse(); - } catch (Exception\InvalidShortCodeException $e) { - $this->logger->warning( - 'Provided short code {shortCode} does not belong to any URL. {e}', - ['e' => $e, 'shortCode' => $shortCode] - ); - return new JsonResponse([ - 'error' => RestUtils::getRestErrorCodeFromException($e), - '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 = - '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), - 'message' => sprintf($messagePlaceholder, $shortCode, $e->getVisitsThreshold()), - ], self::STATUS_BAD_REQUEST); - } + $this->deleteShortUrlService->deleteByShortCode($shortCode); + return new EmptyResponse(); } } diff --git a/module/Rest/src/Action/ShortUrl/EditShortUrlAction.php b/module/Rest/src/Action/ShortUrl/EditShortUrlAction.php index fe609e03..33796f7d 100644 --- a/module/Rest/src/Action/ShortUrl/EditShortUrlAction.php +++ b/module/Rest/src/Action/ShortUrl/EditShortUrlAction.php @@ -7,15 +7,10 @@ namespace Shlinkio\Shlink\Rest\Action\ShortUrl; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Log\LoggerInterface; -use Shlinkio\Shlink\Core\Exception; use Shlinkio\Shlink\Core\Model\ShortUrlMeta; use Shlinkio\Shlink\Core\Service\ShortUrlServiceInterface; use Shlinkio\Shlink\Rest\Action\AbstractRestAction; -use Shlinkio\Shlink\Rest\Util\RestUtils; use Zend\Diactoros\Response\EmptyResponse; -use Zend\Diactoros\Response\JsonResponse; - -use function sprintf; class EditShortUrlAction extends AbstractRestAction { @@ -31,38 +26,12 @@ class EditShortUrlAction extends AbstractRestAction $this->shortUrlService = $shortUrlService; } - /** - * Process an incoming server request and return a response, optionally delegating - * to the next middleware component to create the response. - * - * @param ServerRequestInterface $request - * - * @return ResponseInterface - * @throws \InvalidArgumentException - */ public function handle(ServerRequestInterface $request): ResponseInterface { $postData = (array) $request->getParsedBody(); $shortCode = $request->getAttribute('shortCode', ''); - try { - $this->shortUrlService->updateMetadataByShortCode( - $shortCode, - ShortUrlMeta::createFromRawData($postData) - ); - return new EmptyResponse(); - } catch (Exception\InvalidShortCodeException $e) { - $this->logger->warning('Provided data is invalid. {e}', ['e' => $e]); - return new JsonResponse([ - 'error' => RestUtils::getRestErrorCodeFromException($e), - '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' => 'Provided data is invalid.', - ], self::STATUS_BAD_REQUEST); - } + $this->shortUrlService->updateMetadataByShortCode($shortCode, ShortUrlMeta::createFromRawData($postData)); + return new EmptyResponse(); } } diff --git a/module/Rest/src/Action/ShortUrl/EditShortUrlTagsAction.php b/module/Rest/src/Action/ShortUrl/EditShortUrlTagsAction.php index 4daa0fac..208be169 100644 --- a/module/Rest/src/Action/ShortUrl/EditShortUrlTagsAction.php +++ b/module/Rest/src/Action/ShortUrl/EditShortUrlTagsAction.php @@ -7,14 +7,11 @@ namespace Shlinkio\Shlink\Rest\Action\ShortUrl; use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Log\LoggerInterface; -use Shlinkio\Shlink\Core\Exception\InvalidShortCodeException; +use Shlinkio\Shlink\Core\Exception\ValidationException; use Shlinkio\Shlink\Core\Service\ShortUrlServiceInterface; use Shlinkio\Shlink\Rest\Action\AbstractRestAction; -use Shlinkio\Shlink\Rest\Util\RestUtils; use Zend\Diactoros\Response\JsonResponse; -use function sprintf; - class EditShortUrlTagsAction extends AbstractRestAction { protected const ROUTE_PATH = '/short-urls/{shortCode}/tags'; @@ -29,32 +26,19 @@ class EditShortUrlTagsAction extends AbstractRestAction $this->shortUrlService = $shortUrlService; } - /** - * @param Request $request - * @return Response - * @throws \InvalidArgumentException - */ public function handle(Request $request): Response { $shortCode = $request->getAttribute('shortCode'); $bodyParams = $request->getParsedBody(); if (! isset($bodyParams['tags'])) { - return new JsonResponse([ - 'error' => RestUtils::INVALID_ARGUMENT_ERROR, - 'message' => 'A list of tags was not provided', - ], self::STATUS_BAD_REQUEST); + throw ValidationException::fromArray([ + 'tags' => 'List of tags has to be provided', + ]); } $tags = $bodyParams['tags']; - try { - $shortUrl = $this->shortUrlService->setTagsByShortCode($shortCode, $tags); - return new JsonResponse(['tags' => $shortUrl->getTags()->toArray()]); - } catch (InvalidShortCodeException $e) { - return new JsonResponse([ - 'error' => RestUtils::getRestErrorCodeFromException($e), - 'message' => sprintf('No URL found for short code "%s"', $shortCode), - ], self::STATUS_NOT_FOUND); - } + $shortUrl = $this->shortUrlService->setTagsByShortCode($shortCode, $tags); + return new JsonResponse(['tags' => $shortUrl->getTags()->toArray()]); } } diff --git a/module/Rest/src/Action/ShortUrl/ListShortUrlsAction.php b/module/Rest/src/Action/ShortUrl/ListShortUrlsAction.php index 8c4211c8..87e7930b 100644 --- a/module/Rest/src/Action/ShortUrl/ListShortUrlsAction.php +++ b/module/Rest/src/Action/ShortUrl/ListShortUrlsAction.php @@ -4,15 +4,16 @@ declare(strict_types=1); namespace Shlinkio\Shlink\Rest\Action\ShortUrl; -use Exception; +use Cake\Chronos\Chronos; +use InvalidArgumentException; use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Log\LoggerInterface; use Shlinkio\Shlink\Common\Paginator\Util\PaginatorUtilsTrait; +use Shlinkio\Shlink\Common\Util\DateRange; use Shlinkio\Shlink\Core\Service\ShortUrlServiceInterface; use Shlinkio\Shlink\Core\Transformer\ShortUrlDataTransformer; use Shlinkio\Shlink\Rest\Action\AbstractRestAction; -use Shlinkio\Shlink\Rest\Util\RestUtils; use Zend\Diactoros\Response\JsonResponse; class ListShortUrlsAction extends AbstractRestAction @@ -40,23 +41,15 @@ class ListShortUrlsAction extends AbstractRestAction /** * @param Request $request * @return Response - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public function handle(Request $request): Response { - try { - $params = $this->queryToListParams($request->getQueryParams()); - $shortUrls = $this->shortUrlService->listShortUrls(...$params); - return new JsonResponse(['shortUrls' => $this->serializePaginator($shortUrls, new ShortUrlDataTransformer( - $this->domainConfig - ))]); - } catch (Exception $e) { - $this->logger->error('Unexpected error while listing short URLs. {e}', ['e' => $e]); - return new JsonResponse([ - 'error' => RestUtils::UNKNOWN_ERROR, - 'message' => 'Unexpected error occurred', - ], self::STATUS_INTERNAL_SERVER_ERROR); - } + $params = $this->queryToListParams($request->getQueryParams()); + $shortUrls = $this->shortUrlService->listShortUrls(...$params); + return new JsonResponse(['shortUrls' => $this->serializePaginator($shortUrls, new ShortUrlDataTransformer( + $this->domainConfig + ))]); } /** @@ -70,6 +63,15 @@ class ListShortUrlsAction extends AbstractRestAction $query['searchTerm'] ?? null, $query['tags'] ?? [], $query['orderBy'] ?? null, + $this->determineDateRangeFromQuery($query), ]; } + + private function determineDateRangeFromQuery(array $query): DateRange + { + return new DateRange( + isset($query['startDate']) ? Chronos::parse($query['startDate']) : null, + isset($query['endDate']) ? Chronos::parse($query['endDate']) : null + ); + } } diff --git a/module/Rest/src/Action/ShortUrl/ResolveShortUrlAction.php b/module/Rest/src/Action/ShortUrl/ResolveShortUrlAction.php index 57d3cd62..e041f4dc 100644 --- a/module/Rest/src/Action/ShortUrl/ResolveShortUrlAction.php +++ b/module/Rest/src/Action/ShortUrl/ResolveShortUrlAction.php @@ -4,20 +4,15 @@ declare(strict_types=1); namespace Shlinkio\Shlink\Rest\Action\ShortUrl; -use Exception; +use InvalidArgumentException; use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Log\LoggerInterface; -use Shlinkio\Shlink\Core\Exception\EntityDoesNotExistException; -use Shlinkio\Shlink\Core\Exception\InvalidShortCodeException; use Shlinkio\Shlink\Core\Service\UrlShortenerInterface; use Shlinkio\Shlink\Core\Transformer\ShortUrlDataTransformer; use Shlinkio\Shlink\Rest\Action\AbstractRestAction; -use Shlinkio\Shlink\Rest\Util\RestUtils; use Zend\Diactoros\Response\JsonResponse; -use function sprintf; - class ResolveShortUrlAction extends AbstractRestAction { protected const ROUTE_PATH = '/short-urls/{shortCode}'; @@ -41,7 +36,7 @@ class ResolveShortUrlAction extends AbstractRestAction /** * @param Request $request * @return Response - * @throws \InvalidArgumentException + * @throws InvalidArgumentException */ public function handle(Request $request): Response { @@ -49,27 +44,7 @@ class ResolveShortUrlAction extends AbstractRestAction $domain = $request->getQueryParams()['domain'] ?? null; $transformer = new ShortUrlDataTransformer($this->domainConfig); - try { - $url = $this->urlShortener->shortCodeToUrl($shortCode, $domain); - return new JsonResponse($transformer->transform($url)); - } catch (InvalidShortCodeException $e) { - $this->logger->warning('Provided short code with invalid format. {e}', ['e' => $e]); - return new JsonResponse([ - 'error' => RestUtils::getRestErrorCodeFromException($e), - '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('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' => 'Unexpected error occurred', - ], self::STATUS_INTERNAL_SERVER_ERROR); - } + $url = $this->urlShortener->shortCodeToUrl($shortCode, $domain); + return new JsonResponse($transformer->transform($url)); } } diff --git a/module/Rest/src/Action/ShortUrl/SingleStepCreateShortUrlAction.php b/module/Rest/src/Action/ShortUrl/SingleStepCreateShortUrlAction.php index 327df46e..834c6b12 100644 --- a/module/Rest/src/Action/ShortUrl/SingleStepCreateShortUrlAction.php +++ b/module/Rest/src/Action/ShortUrl/SingleStepCreateShortUrlAction.php @@ -6,7 +6,7 @@ namespace Shlinkio\Shlink\Rest\Action\ShortUrl; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Log\LoggerInterface; -use Shlinkio\Shlink\Core\Exception\InvalidArgumentException; +use Shlinkio\Shlink\Core\Exception\ValidationException; use Shlinkio\Shlink\Core\Model\CreateShortUrlData; use Shlinkio\Shlink\Core\Service\UrlShortenerInterface; use Shlinkio\Shlink\Rest\Service\ApiKeyServiceInterface; @@ -33,19 +33,22 @@ class SingleStepCreateShortUrlAction extends AbstractCreateShortUrlAction /** * @param Request $request * @return CreateShortUrlData - * @throws \InvalidArgumentException - * @throws InvalidArgumentException + * @throws ValidationException */ protected function buildShortUrlData(Request $request): CreateShortUrlData { $query = $request->getQueryParams(); if (! $this->apiKeyService->check($query['apiKey'] ?? '')) { - throw new InvalidArgumentException('No API key was provided or it is not valid'); + throw ValidationException::fromArray([ + 'apiKey' => 'No API key was provided or it is not valid', + ]); } if (! isset($query['longUrl'])) { - throw new InvalidArgumentException('A URL was not provided'); + throw ValidationException::fromArray([ + 'longUrl' => 'A URL was not provided', + ]); } return new CreateShortUrlData(new Uri($query['longUrl'])); diff --git a/module/Rest/src/Action/Tag/UpdateTagAction.php b/module/Rest/src/Action/Tag/UpdateTagAction.php index d494673c..175ed0a0 100644 --- a/module/Rest/src/Action/Tag/UpdateTagAction.php +++ b/module/Rest/src/Action/Tag/UpdateTagAction.php @@ -7,15 +7,10 @@ namespace Shlinkio\Shlink\Rest\Action\Tag; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Log\LoggerInterface; -use Shlinkio\Shlink\Core\Exception\EntityDoesNotExistException; -use Shlinkio\Shlink\Core\Exception\TagConflictException; +use Shlinkio\Shlink\Core\Exception\ValidationException; use Shlinkio\Shlink\Core\Service\Tag\TagServiceInterface; use Shlinkio\Shlink\Rest\Action\AbstractRestAction; -use Shlinkio\Shlink\Rest\Util\RestUtils; use Zend\Diactoros\Response\EmptyResponse; -use Zend\Diactoros\Response\JsonResponse; - -use function sprintf; class UpdateTagAction extends AbstractRestAction { @@ -44,30 +39,13 @@ class UpdateTagAction extends AbstractRestAction { $body = $request->getParsedBody(); if (! isset($body['oldName'], $body['newName'])) { - return new JsonResponse([ - 'error' => RestUtils::INVALID_ARGUMENT_ERROR, - 'message' => - 'You have to provide both \'oldName\' and \'newName\' params in order to properly rename the tag', - ], self::STATUS_BAD_REQUEST); + throw ValidationException::fromArray([ + 'oldName' => 'oldName is required', + 'newName' => 'newName is required', + ]); } - try { - $this->tagService->renameTag($body['oldName'], $body['newName']); - return new EmptyResponse(); - } catch (EntityDoesNotExistException $e) { - return new JsonResponse([ - 'error' => RestUtils::NOT_FOUND_ERROR, - 'message' => sprintf('It was not possible to find a tag with name %s', $body['oldName']), - ], self::STATUS_NOT_FOUND); - } catch (TagConflictException $e) { - return new JsonResponse([ - 'error' => 'TAG_CONFLICT', - 'message' => sprintf( - 'You cannot rename tag %s to %s, because it already exists', - $body['oldName'], - $body['newName'] - ), - ], self::STATUS_CONFLICT); - } + $this->tagService->renameTag($body['oldName'], $body['newName']); + return new EmptyResponse(); } } diff --git a/module/Rest/src/Action/Visit/GetVisitsAction.php b/module/Rest/src/Action/Visit/GetVisitsAction.php index 222a76b8..ca8c2838 100644 --- a/module/Rest/src/Action/Visit/GetVisitsAction.php +++ b/module/Rest/src/Action/Visit/GetVisitsAction.php @@ -7,16 +7,12 @@ namespace Shlinkio\Shlink\Rest\Action\Visit; use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Log\LoggerInterface; -use Shlinkio\Shlink\Common\Exception\InvalidArgumentException; use Shlinkio\Shlink\Common\Paginator\Util\PaginatorUtilsTrait; use Shlinkio\Shlink\Core\Model\VisitsParams; use Shlinkio\Shlink\Core\Service\VisitsTrackerInterface; use Shlinkio\Shlink\Rest\Action\AbstractRestAction; -use Shlinkio\Shlink\Rest\Util\RestUtils; use Zend\Diactoros\Response\JsonResponse; -use function sprintf; - class GetVisitsAction extends AbstractRestAction { use PaginatorUtilsTrait; @@ -33,27 +29,13 @@ class GetVisitsAction extends AbstractRestAction $this->visitsTracker = $visitsTracker; } - /** - * @param Request $request - * @return Response - * @throws \InvalidArgumentException - */ public function handle(Request $request): Response { $shortCode = $request->getAttribute('shortCode'); + $visits = $this->visitsTracker->info($shortCode, VisitsParams::fromRawData($request->getQueryParams())); - try { - $visits = $this->visitsTracker->info($shortCode, VisitsParams::fromRawData($request->getQueryParams())); - - return new JsonResponse([ - 'visits' => $this->serializePaginator($visits), - ]); - } catch (InvalidArgumentException $e) { - $this->logger->warning('Provided nonexistent short code {e}', ['e' => $e]); - return new JsonResponse([ - 'error' => RestUtils::getRestErrorCodeFromException($e), - 'message' => sprintf('Provided short code %s does not exist', $shortCode), - ], self::STATUS_NOT_FOUND); - } + return new JsonResponse([ + 'visits' => $this->serializePaginator($visits), + ]); } } diff --git a/module/Rest/src/Authentication/JWTService.php b/module/Rest/src/Authentication/JWTService.php index 841527e4..77ec6728 100644 --- a/module/Rest/src/Authentication/JWTService.php +++ b/module/Rest/src/Authentication/JWTService.php @@ -12,6 +12,7 @@ use UnexpectedValueException; use function time; +/** @deprecated */ class JWTService implements JWTServiceInterface { /** @var AppOptions */ diff --git a/module/Rest/src/Authentication/Plugin/ApiKeyHeaderPlugin.php b/module/Rest/src/Authentication/Plugin/ApiKeyHeaderPlugin.php index d5cd38f9..14735f9a 100644 --- a/module/Rest/src/Authentication/Plugin/ApiKeyHeaderPlugin.php +++ b/module/Rest/src/Authentication/Plugin/ApiKeyHeaderPlugin.php @@ -8,7 +8,6 @@ use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Shlinkio\Shlink\Rest\Exception\VerifyAuthenticationException; use Shlinkio\Shlink\Rest\Service\ApiKeyServiceInterface; -use Shlinkio\Shlink\Rest\Util\RestUtils; class ApiKeyHeaderPlugin implements AuthenticationPluginInterface { @@ -28,14 +27,9 @@ class ApiKeyHeaderPlugin implements AuthenticationPluginInterface public function verify(ServerRequestInterface $request): void { $apiKey = $request->getHeaderLine(self::HEADER_NAME); - if ($this->apiKeyService->check($apiKey)) { - return; + if (! $this->apiKeyService->check($apiKey)) { + throw VerifyAuthenticationException::forInvalidApiKey(); } - - throw VerifyAuthenticationException::withError( - RestUtils::INVALID_API_KEY_ERROR, - 'Provided API key does not exist or is invalid.' - ); } public function update(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface diff --git a/module/Rest/src/Authentication/Plugin/AuthorizationHeaderPlugin.php b/module/Rest/src/Authentication/Plugin/AuthorizationHeaderPlugin.php index e5280ac6..bf75d09b 100644 --- a/module/Rest/src/Authentication/Plugin/AuthorizationHeaderPlugin.php +++ b/module/Rest/src/Authentication/Plugin/AuthorizationHeaderPlugin.php @@ -8,7 +8,6 @@ use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Shlinkio\Shlink\Rest\Authentication\JWTServiceInterface; use Shlinkio\Shlink\Rest\Exception\VerifyAuthenticationException; -use Shlinkio\Shlink\Rest\Util\RestUtils; use Throwable; use function count; @@ -16,6 +15,7 @@ use function explode; use function sprintf; use function strtolower; +/** @deprecated */ class AuthorizationHeaderPlugin implements AuthenticationPluginInterface { public const HEADER_NAME = 'Authorization'; @@ -37,19 +37,13 @@ class AuthorizationHeaderPlugin implements AuthenticationPluginInterface $authToken = $request->getHeaderLine(self::HEADER_NAME); $authTokenParts = explode(' ', $authToken); if (count($authTokenParts) === 1) { - throw VerifyAuthenticationException::withError( - RestUtils::INVALID_AUTHORIZATION_ERROR, - sprintf('You need to provide the Bearer type in the %s header.', self::HEADER_NAME) - ); + throw VerifyAuthenticationException::forMissingAuthType(); } // Make sure the authorization type is Bearer [$authType, $jwt] = $authTokenParts; if (strtolower($authType) !== 'bearer') { - throw VerifyAuthenticationException::withError( - RestUtils::INVALID_AUTHORIZATION_ERROR, - sprintf('Provided authorization type %s is not supported. Use Bearer instead.', $authType) - ); + throw VerifyAuthenticationException::forInvalidAuthType($authType); } try { @@ -57,21 +51,13 @@ class AuthorizationHeaderPlugin implements AuthenticationPluginInterface throw $this->createInvalidTokenError(); } } catch (Throwable $e) { - throw $this->createInvalidTokenError($e); + throw $this->createInvalidTokenError(); } } - private function createInvalidTokenError(?Throwable $prev = null): VerifyAuthenticationException + private function createInvalidTokenError(): VerifyAuthenticationException { - return VerifyAuthenticationException::withError( - RestUtils::INVALID_AUTH_TOKEN_ERROR, - 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 - ), - $prev - ); + return VerifyAuthenticationException::forInvalidAuthToken(); } public function update(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface diff --git a/module/Rest/src/Authentication/RequestToHttpAuthPlugin.php b/module/Rest/src/Authentication/RequestToHttpAuthPlugin.php index f0cc0fe4..c10c0321 100644 --- a/module/Rest/src/Authentication/RequestToHttpAuthPlugin.php +++ b/module/Rest/src/Authentication/RequestToHttpAuthPlugin.php @@ -4,9 +4,8 @@ declare(strict_types=1); namespace Shlinkio\Shlink\Rest\Authentication; -use Psr\Container; use Psr\Http\Message\ServerRequestInterface; -use Shlinkio\Shlink\Rest\Exception\NoAuthenticationException; +use Shlinkio\Shlink\Rest\Exception\MissingAuthenticationException; use function array_filter; use function array_reduce; @@ -30,16 +29,12 @@ class RequestToHttpAuthPlugin implements RequestToHttpAuthPluginInterface } /** - * @throws Container\ContainerExceptionInterface - * @throws NoAuthenticationException + * @throws MissingAuthenticationException */ public function fromRequest(ServerRequestInterface $request): Plugin\AuthenticationPluginInterface { if (! $this->hasAnySupportedHeader($request)) { - throw NoAuthenticationException::fromExpectedTypes([ - Plugin\ApiKeyHeaderPlugin::HEADER_NAME, - Plugin\AuthorizationHeaderPlugin::HEADER_NAME, - ]); + throw MissingAuthenticationException::fromExpectedTypes(self::SUPPORTED_AUTH_HEADERS); } return $this->authPluginManager->get($this->getFirstAvailableHeader($request)); diff --git a/module/Rest/src/Authentication/RequestToHttpAuthPluginInterface.php b/module/Rest/src/Authentication/RequestToHttpAuthPluginInterface.php index 18e68ee2..b8002431 100644 --- a/module/Rest/src/Authentication/RequestToHttpAuthPluginInterface.php +++ b/module/Rest/src/Authentication/RequestToHttpAuthPluginInterface.php @@ -4,15 +4,13 @@ declare(strict_types=1); namespace Shlinkio\Shlink\Rest\Authentication; -use Psr\Container; use Psr\Http\Message\ServerRequestInterface; -use Shlinkio\Shlink\Rest\Exception\NoAuthenticationException; +use Shlinkio\Shlink\Rest\Exception\MissingAuthenticationException; interface RequestToHttpAuthPluginInterface { /** - * @throws Container\ContainerExceptionInterface - * @throws NoAuthenticationException + * @throws MissingAuthenticationException */ public function fromRequest(ServerRequestInterface $request): Plugin\AuthenticationPluginInterface; } diff --git a/module/Rest/src/ConfigProvider.php b/module/Rest/src/ConfigProvider.php index 11e6f811..0c0e99a5 100644 --- a/module/Rest/src/ConfigProvider.php +++ b/module/Rest/src/ConfigProvider.php @@ -4,19 +4,26 @@ declare(strict_types=1); namespace Shlinkio\Shlink\Rest; -use Zend\Config\Factory; -use Zend\Stdlib\Glob; - +use function Shlinkio\Shlink\Common\loadConfigFromGlob; use function sprintf; class ConfigProvider { - private const ROUTES_PREFIX = '/rest/v{version:1}'; + private const ROUTES_PREFIX = '/rest/v{version:1|2}'; + + /** @var callable */ + private $loadConfig; + + public function __construct(?callable $loadConfig = null) + { + $this->loadConfig = $loadConfig ?? function (string $glob) { + return loadConfigFromGlob($glob); + }; + } public function __invoke() { - /** @var array $config */ - $config = Factory::fromFiles(Glob::glob(__DIR__ . '/../config/{,*.}config.php', Glob::GLOB_BRACE)); + $config = ($this->loadConfig)(__DIR__ . '/../config/{,*.}config.php'); return $this->applyRoutesPrefix($config); } diff --git a/module/Rest/src/ErrorHandler/JsonErrorResponseGenerator.php b/module/Rest/src/ErrorHandler/JsonErrorResponseGenerator.php deleted file mode 100644 index ca9ed12c..00000000 --- a/module/Rest/src/ErrorHandler/JsonErrorResponseGenerator.php +++ /dev/null @@ -1,44 +0,0 @@ -getStatusCode(); - $responsePhrase = $status < 400 ? 'Internal Server Error' : $response->getReasonPhrase(); - $status = $status < 400 ? self::STATUS_INTERNAL_SERVER_ERROR : $status; - - return new JsonResponse([ - 'error' => $this->responsePhraseToCode($responsePhrase), - 'message' => $responsePhrase, - ], $status); - } - - private function responsePhraseToCode(string $responsePhrase): string - { - return strtoupper(str_replace(' ', '_', $responsePhrase)); - } -} diff --git a/module/Rest/src/Exception/AuthenticationException.php b/module/Rest/src/Exception/AuthenticationException.php index 1613bac5..3e60edb6 100644 --- a/module/Rest/src/Exception/AuthenticationException.php +++ b/module/Rest/src/Exception/AuthenticationException.php @@ -6,6 +6,7 @@ namespace Shlinkio\Shlink\Rest\Exception; use Throwable; +/** @deprecated */ class AuthenticationException extends RuntimeException { public static function expiredJWT(?Throwable $prev = null): self diff --git a/module/Rest/src/Exception/MissingAuthenticationException.php b/module/Rest/src/Exception/MissingAuthenticationException.php new file mode 100644 index 00000000..c00cb3e0 --- /dev/null +++ b/module/Rest/src/Exception/MissingAuthenticationException.php @@ -0,0 +1,36 @@ +detail = $e->getMessage(); + $e->title = self::TITLE; + $e->type = self::TYPE; + $e->status = StatusCodeInterface::STATUS_UNAUTHORIZED; + $e->additional = ['expectedTypes' => $expectedTypes]; + + return $e; + } +} diff --git a/module/Rest/src/Exception/NoAuthenticationException.php b/module/Rest/src/Exception/NoAuthenticationException.php deleted file mode 100644 index b5e8bfc8..00000000 --- a/module/Rest/src/Exception/NoAuthenticationException.php +++ /dev/null @@ -1,19 +0,0 @@ -errorCode = $errorCode; - $this->publicMessage = $publicMessage; + public static function forInvalidApiKey(): self + { + $e = new self('Provided API key does not exist or is invalid.'); + + $e->detail = $e->getMessage(); + $e->title = 'Invalid API key'; + $e->type = 'INVALID_API_KEY'; + $e->status = StatusCodeInterface::STATUS_UNAUTHORIZED; + + return $e; } - public static function withError(string $errorCode, string $publicMessage, ?Throwable $prev = null): self + /** @deprecated */ + public static function forInvalidAuthToken(): self { - return new self( - $errorCode, - $publicMessage, - sprintf('Authentication verification failed with the public message "%s"', $publicMessage), - 0, - $prev + $e = new self( + 'Missing or invalid auth token provided. Perform a new authentication request and send provided ' + . 'token on every new request on the Authorization header' ); + + $e->detail = $e->getMessage(); + $e->title = 'Invalid auth token'; + $e->type = 'INVALID_AUTH_TOKEN'; + $e->status = StatusCodeInterface::STATUS_UNAUTHORIZED; + + return $e; } - public function getErrorCode(): string + /** @deprecated */ + public static function forMissingAuthType(): self { - return $this->errorCode; + $e = new self('You need to provide the Bearer type in the Authorization header.'); + + $e->detail = $e->getMessage(); + $e->title = 'Invalid authorization'; + $e->type = 'INVALID_AUTHORIZATION'; + $e->status = StatusCodeInterface::STATUS_UNAUTHORIZED; + + return $e; } - public function getPublicMessage(): string + /** @deprecated */ + public static function forInvalidAuthType(string $providedType): self { - return $this->publicMessage; + $e = new self(sprintf('Provided authorization type %s is not supported. Use Bearer instead.', $providedType)); + + $e->detail = $e->getMessage(); + $e->title = 'Invalid authorization'; + $e->type = 'INVALID_AUTHORIZATION'; + $e->status = StatusCodeInterface::STATUS_UNAUTHORIZED; + + return $e; } } diff --git a/module/Rest/src/Middleware/AuthenticationMiddleware.php b/module/Rest/src/Middleware/AuthenticationMiddleware.php index 855f5490..4fd44bcf 100644 --- a/module/Rest/src/Middleware/AuthenticationMiddleware.php +++ b/module/Rest/src/Middleware/AuthenticationMiddleware.php @@ -6,54 +6,28 @@ namespace Shlinkio\Shlink\Rest\Middleware; use Fig\Http\Message\RequestMethodInterface; use Fig\Http\Message\StatusCodeInterface; -use Psr\Container\ContainerExceptionInterface; 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 Psr\Log\LoggerInterface; -use Psr\Log\NullLogger; -use Shlinkio\Shlink\Rest\Authentication\RequestToHttpAuthPlugin; use Shlinkio\Shlink\Rest\Authentication\RequestToHttpAuthPluginInterface; -use Shlinkio\Shlink\Rest\Exception\NoAuthenticationException; -use Shlinkio\Shlink\Rest\Exception\VerifyAuthenticationException; -use Shlinkio\Shlink\Rest\Util\RestUtils; -use Zend\Diactoros\Response\JsonResponse; use Zend\Expressive\Router\RouteResult; use function Functional\contains; -use function implode; -use function sprintf; class AuthenticationMiddleware implements MiddlewareInterface, StatusCodeInterface, RequestMethodInterface { - /** @var LoggerInterface */ - private $logger; /** @var array */ private $routesWhitelist; /** @var RequestToHttpAuthPluginInterface */ private $requestToAuthPlugin; - public function __construct( - RequestToHttpAuthPluginInterface $requestToAuthPlugin, - array $routesWhitelist, - ?LoggerInterface $logger = null - ) { + public function __construct(RequestToHttpAuthPluginInterface $requestToAuthPlugin, array $routesWhitelist) + { $this->routesWhitelist = $routesWhitelist; $this->requestToAuthPlugin = $requestToAuthPlugin; - $this->logger = $logger ?: new NullLogger(); } - /** - * Process an incoming server request and return a response, optionally delegating - * to the next middleware component to create the response. - * - * @param Request $request - * @param RequestHandlerInterface $handler - * - * @return Response - * @throws \InvalidArgumentException - */ public function process(Request $request, RequestHandlerInterface $handler): Response { /** @var RouteResult|null $routeResult */ @@ -67,33 +41,10 @@ class AuthenticationMiddleware implements MiddlewareInterface, StatusCodeInterfa return $handler->handle($request); } - try { - $plugin = $this->requestToAuthPlugin->fromRequest($request); - } catch (ContainerExceptionInterface | NoAuthenticationException $e) { - $this->logger->warning('Invalid or no authentication provided. {e}', ['e' => $e]); - return $this->createErrorResponse(sprintf( - 'Expected one of the following authentication headers, but none were provided, ["%s"]', - implode('", "', RequestToHttpAuthPlugin::SUPPORTED_AUTH_HEADERS) - )); - } + $plugin = $this->requestToAuthPlugin->fromRequest($request); + $plugin->verify($request); + $response = $handler->handle($request); - try { - $plugin->verify($request); - $response = $handler->handle($request); - return $plugin->update($request, $response); - } catch (VerifyAuthenticationException $e) { - $this->logger->warning('Authentication verification failed. {e}', ['e' => $e]); - return $this->createErrorResponse($e->getPublicMessage(), $e->getErrorCode()); - } - } - - private function createErrorResponse( - string $message, - string $errorCode = RestUtils::INVALID_AUTHORIZATION_ERROR - ): JsonResponse { - return new JsonResponse([ - 'error' => $errorCode, - 'message' => $message, - ], self::STATUS_UNAUTHORIZED); + return $plugin->update($request, $response); } } diff --git a/module/Rest/src/Middleware/BackwardsCompatibleProblemDetailsMiddleware.php b/module/Rest/src/Middleware/BackwardsCompatibleProblemDetailsMiddleware.php new file mode 100644 index 00000000..0812c7e0 --- /dev/null +++ b/module/Rest/src/Middleware/BackwardsCompatibleProblemDetailsMiddleware.php @@ -0,0 +1,84 @@ + 'type', + 'message' => 'detail', + ]; + + /** @var array */ + private $defaultTypeFallbacks; + /** @var int */ + private $jsonFlags; + + public function __construct(array $defaultTypeFallbacks, int $jsonFlags) + { + $this->defaultTypeFallbacks = $defaultTypeFallbacks; + $this->jsonFlags = $jsonFlags; + } + + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface + { + $resp = $handler->handle($request); + if ($resp->getHeaderLine('Content-type') !== 'application/problem+json') { + return $resp; + } + + try { + $body = (string) $resp->getBody(); + $payload = json_decode($body); + } catch (Throwable $e) { + return $resp; + } + + $payload = $this->mapStandardErrorTypes($payload, $resp->getStatusCode()); + + if ($this->isVersionOne($request)) { + $payload = $this->makePayloadBackwardsCompatible($payload); + } + + return new JsonResponse($payload, $resp->getStatusCode(), $resp->getHeaders(), $this->jsonFlags); + } + + private function mapStandardErrorTypes(array $payload, int $respStatusCode): array + { + $type = $payload['type'] ?? ''; + if (strpos($type, 'https://httpstatus.es') === 0) { + $payload['type'] = $this->defaultTypeFallbacks[$respStatusCode] ?? $type; + } + + return $payload; + } + + /** @deprecated When Shlink 2 is released, do not chekc the version */ + private function isVersionOne(ServerRequestInterface $request): bool + { + $path = $request->getUri()->getPath(); + return strpos($path, '/v') === false || strpos($path, '/v1') === 0; + } + + /** @deprecated When Shlink v2 is released, do not map old fields */ + private function makePayloadBackwardsCompatible(array $payload): array + { + return reduce_left(self::BACKWARDS_COMPATIBLE_FIELDS, function (string $newKey, string $oldKey, $c, $acc) { + $acc[$oldKey] = $acc[$newKey]; + return $acc; + }, $payload); + } +} diff --git a/module/Rest/src/Middleware/PathVersionMiddleware.php b/module/Rest/src/Middleware/PathVersionMiddleware.php index c08c8dbb..84921710 100644 --- a/module/Rest/src/Middleware/PathVersionMiddleware.php +++ b/module/Rest/src/Middleware/PathVersionMiddleware.php @@ -15,23 +15,12 @@ class PathVersionMiddleware implements MiddlewareInterface { // TODO The /health endpoint needs this middleware in order to work without the version. // Take it into account if this middleware is ever removed. - - /** - * Process an incoming server request and return a response, optionally delegating - * to the next middleware component to create the response. - * - * @param Request $request - * @param RequestHandlerInterface $handler - * - * @return Response - * @throws \InvalidArgumentException - */ public function process(Request $request, RequestHandlerInterface $handler): Response { $uri = $request->getUri(); $path = $uri->getPath(); - // If the path does not begin with the version number, prepend v1 by default for BC compatibility purposes + // If the path does not begin with the version number, prepend v1 by default for BC purposes if (strpos($path, '/v') !== 0) { $request = $request->withUri($uri->withPath('/v1' . $uri->getPath())); } diff --git a/module/Rest/src/Middleware/ShortUrl/CreateShortUrlContentNegotiationMiddleware.php b/module/Rest/src/Middleware/ShortUrl/CreateShortUrlContentNegotiationMiddleware.php index 64da53d5..98b64401 100644 --- a/module/Rest/src/Middleware/ShortUrl/CreateShortUrlContentNegotiationMiddleware.php +++ b/module/Rest/src/Middleware/ShortUrl/CreateShortUrlContentNegotiationMiddleware.php @@ -21,12 +21,6 @@ class CreateShortUrlContentNegotiationMiddleware implements MiddlewareInterface private const PLAIN_TEXT = 'text'; private const JSON = 'json'; - /** - * Process an incoming server request and return a response, optionally delegating - * response creation to a handler. - * @throws \RuntimeException - * @throws \InvalidArgumentException - */ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $response = $handler->handle($request); diff --git a/module/Rest/src/Util/RestUtils.php b/module/Rest/src/Util/RestUtils.php deleted file mode 100644 index d4ad46dc..00000000 --- a/module/Rest/src/Util/RestUtils.php +++ /dev/null @@ -1,48 +0,0 @@ -createShortUrl(['customSlug' => $slug, 'domain' => $domain]); $this->assertEquals(self::STATUS_BAD_REQUEST, $statusCode); - $this->assertEquals(RestUtils::INVALID_SLUG_ERROR, $payload['error']); + $this->assertEquals(self::STATUS_BAD_REQUEST, $payload['status']); + $this->assertEquals($detail, $payload['detail']); + $this->assertEquals($detail, $payload['message']); // Deprecated + $this->assertEquals('INVALID_SLUG', $payload['type']); + $this->assertEquals('INVALID_SLUG', $payload['error']); // Deprecated + $this->assertEquals('Invalid custom slug', $payload['title']); + $this->assertEquals($slug, $payload['customSlug']); + + if ($domain !== null) { + $this->assertEquals($domain, $payload['domain']); + } else { + $this->assertArrayNotHasKey('domain', $payload); + } } /** @test */ @@ -201,6 +216,24 @@ class CreateShortUrlActionTest extends ApiTestCase yield ['http://téstb.shlink.io']; // Redirects to http://tést.shlink.io } + /** @test */ + public function failsToCreateShortUrlWithInvalidOriginalUrl(): void + { + $url = 'https://this-has-to-be-invalid.com'; + $expectedDetail = sprintf('Provided URL %s is invalid. Try with a different one.', $url); + + [$statusCode, $payload] = $this->createShortUrl(['longUrl' => $url]); + + $this->assertEquals(self::STATUS_BAD_REQUEST, $statusCode); + $this->assertEquals(self::STATUS_BAD_REQUEST, $payload['status']); + $this->assertEquals('INVALID_URL', $payload['type']); + $this->assertEquals('INVALID_URL', $payload['error']); // Deprecated + $this->assertEquals($expectedDetail, $payload['detail']); + $this->assertEquals($expectedDetail, $payload['message']); // Deprecated + $this->assertEquals('Invalid URL', $payload['title']); + $this->assertEquals($url, $payload['url']); + } + /** * @return array { * @var int $statusCode diff --git a/module/Rest/test-api/Action/DeleteShortUrlActionTest.php b/module/Rest/test-api/Action/DeleteShortUrlActionTest.php new file mode 100644 index 00000000..4680a6f6 --- /dev/null +++ b/module/Rest/test-api/Action/DeleteShortUrlActionTest.php @@ -0,0 +1,49 @@ +callApiWithKey(self::METHOD_DELETE, '/short-urls/invalid'); + $payload = $this->getJsonResponsePayload($resp); + + $this->assertEquals(self::STATUS_NOT_FOUND, $resp->getStatusCode()); + $this->assertEquals(self::STATUS_NOT_FOUND, $payload['status']); + $this->assertEquals('INVALID_SHORTCODE', $payload['type']); + $this->assertEquals('INVALID_SHORTCODE', $payload['error']); // Deprecated + $this->assertEquals($expectedDetail, $payload['detail']); + $this->assertEquals($expectedDetail, $payload['message']); // Deprecated + $this->assertEquals('Short URL not found', $payload['title']); + $this->assertEquals('invalid', $payload['shortCode']); + } + + /** @test */ + public function unprocessableEntityIsReturnedWhenTryingToDeleteUrlWithTooManyVisits(): void + { + // Generate visits first + for ($i = 0; $i < 20; $i++) { + $this->assertEquals(self::STATUS_FOUND, $this->callShortUrl('abc123')->getStatusCode()); + } + $expectedDetail = 'Impossible to delete short URL with short code "abc123" since it has more than "15" visits.'; + + $resp = $this->callApiWithKey(self::METHOD_DELETE, '/short-urls/abc123'); + $payload = $this->getJsonResponsePayload($resp); + + $this->assertEquals(self::STATUS_UNPROCESSABLE_ENTITY, $resp->getStatusCode()); + $this->assertEquals(self::STATUS_UNPROCESSABLE_ENTITY, $payload['status']); + $this->assertEquals('INVALID_SHORTCODE_DELETION', $payload['type']); + $this->assertEquals('INVALID_SHORTCODE_DELETION', $payload['error']); // Deprecated + $this->assertEquals($expectedDetail, $payload['detail']); + $this->assertEquals($expectedDetail, $payload['message']); // Deprecated + $this->assertEquals('Cannot delete short URL', $payload['title']); + } +} diff --git a/module/Rest/test-api/Action/EditShortUrlActionTest.php b/module/Rest/test-api/Action/EditShortUrlActionTest.php new file mode 100644 index 00000000..bbcb043a --- /dev/null +++ b/module/Rest/test-api/Action/EditShortUrlActionTest.php @@ -0,0 +1,48 @@ +callApiWithKey(self::METHOD_PATCH, '/short-urls/invalid', [RequestOptions::JSON => []]); + $payload = $this->getJsonResponsePayload($resp); + + $this->assertEquals(self::STATUS_NOT_FOUND, $resp->getStatusCode()); + $this->assertEquals(self::STATUS_NOT_FOUND, $payload['status']); + $this->assertEquals('INVALID_SHORTCODE', $payload['type']); + $this->assertEquals('INVALID_SHORTCODE', $payload['error']); // Deprecated + $this->assertEquals($expectedDetail, $payload['detail']); + $this->assertEquals($expectedDetail, $payload['message']); // Deprecated + $this->assertEquals('Short URL not found', $payload['title']); + $this->assertEquals('invalid', $payload['shortCode']); + } + + /** @test */ + public function providingInvalidDataReturnsBadRequest(): void + { + $expectedDetail = 'Provided data is not valid'; + + $resp = $this->callApiWithKey(self::METHOD_PATCH, '/short-urls/invalid', [RequestOptions::JSON => [ + 'maxVisits' => 'not_a_number', + ]]); + $payload = $this->getJsonResponsePayload($resp); + + $this->assertEquals(self::STATUS_BAD_REQUEST, $resp->getStatusCode()); + $this->assertEquals(self::STATUS_BAD_REQUEST, $payload['status']); + $this->assertEquals('INVALID_ARGUMENT', $payload['type']); + $this->assertEquals('INVALID_ARGUMENT', $payload['error']); // Deprecated + $this->assertEquals($expectedDetail, $payload['detail']); + $this->assertEquals($expectedDetail, $payload['message']); // Deprecated + $this->assertEquals('Invalid data', $payload['title']); + } +} diff --git a/module/Rest/test-api/Action/EditShortUrlTagsActionTest.php b/module/Rest/test-api/Action/EditShortUrlTagsActionTest.php new file mode 100644 index 00000000..e2922092 --- /dev/null +++ b/module/Rest/test-api/Action/EditShortUrlTagsActionTest.php @@ -0,0 +1,48 @@ +callApiWithKey(self::METHOD_PUT, '/short-urls/abc123/tags', [RequestOptions::JSON => []]); + $payload = $this->getJsonResponsePayload($resp); + + $this->assertEquals(self::STATUS_BAD_REQUEST, $resp->getStatusCode()); + $this->assertEquals(self::STATUS_BAD_REQUEST, $payload['status']); + $this->assertEquals('INVALID_ARGUMENT', $payload['type']); + $this->assertEquals('INVALID_ARGUMENT', $payload['error']); // Deprecated + $this->assertEquals($expectedDetail, $payload['detail']); + $this->assertEquals($expectedDetail, $payload['message']); // Deprecated + $this->assertEquals('Invalid data', $payload['title']); + } + + /** @test */ + public function providingInvalidShortCodeReturnsBadRequest(): void + { + $expectedDetail = 'No URL found with short code "invalid"'; + + $resp = $this->callApiWithKey(self::METHOD_PUT, '/short-urls/invalid/tags', [RequestOptions::JSON => [ + 'tags' => ['foo', 'bar'], + ]]); + $payload = $this->getJsonResponsePayload($resp); + + $this->assertEquals(self::STATUS_NOT_FOUND, $resp->getStatusCode()); + $this->assertEquals(self::STATUS_NOT_FOUND, $payload['status']); + $this->assertEquals('INVALID_SHORTCODE', $payload['type']); + $this->assertEquals('INVALID_SHORTCODE', $payload['error']); // Deprecated + $this->assertEquals($expectedDetail, $payload['detail']); + $this->assertEquals($expectedDetail, $payload['message']); // Deprecated + $this->assertEquals('Short URL not found', $payload['title']); + $this->assertEquals('invalid', $payload['shortCode']); + } +} diff --git a/module/Rest/test-api/Action/GetVisitsActionTest.php b/module/Rest/test-api/Action/GetVisitsActionTest.php new file mode 100644 index 00000000..0db06848 --- /dev/null +++ b/module/Rest/test-api/Action/GetVisitsActionTest.php @@ -0,0 +1,28 @@ +callApiWithKey(self::METHOD_GET, '/short-urls/invalid/visits'); + $payload = $this->getJsonResponsePayload($resp); + + $this->assertEquals(self::STATUS_NOT_FOUND, $resp->getStatusCode()); + $this->assertEquals(self::STATUS_NOT_FOUND, $payload['status']); + $this->assertEquals('INVALID_SHORTCODE', $payload['type']); + $this->assertEquals('INVALID_SHORTCODE', $payload['error']); // Deprecated + $this->assertEquals($expectedDetail, $payload['detail']); + $this->assertEquals($expectedDetail, $payload['message']); // Deprecated + $this->assertEquals('Short URL not found', $payload['title']); + $this->assertEquals('invalid', $payload['shortCode']); + } +} diff --git a/module/Rest/test-api/Action/ListShortUrlsTest.php b/module/Rest/test-api/Action/ListShortUrlsTest.php index d2171b3a..0952a627 100644 --- a/module/Rest/test-api/Action/ListShortUrlsTest.php +++ b/module/Rest/test-api/Action/ListShortUrlsTest.php @@ -4,107 +4,160 @@ declare(strict_types=1); namespace ShlinkioApiTest\Shlink\Rest\Action; +use Cake\Chronos\Chronos; +use GuzzleHttp\RequestOptions; use Shlinkio\Shlink\TestUtils\ApiTest\ApiTestCase; +use function count; + class ListShortUrlsTest extends ApiTestCase { - /** @test */ - public function shortUrlsAreProperlyListed(): void + private const SHORT_URL_SHLINK = [ + 'shortCode' => 'abc123', + 'shortUrl' => 'http://doma.in/abc123', + 'longUrl' => 'https://shlink.io', + 'dateCreated' => '2018-05-01T00:00:00+00:00', + 'visitsCount' => 3, + 'tags' => ['foo'], + 'meta' => [ + 'validSince' => null, + 'validUntil' => null, + 'maxVisits' => null, + ], + 'originalUrl' => 'https://shlink.io', + ]; + private const SHORT_URL_CUSTOM_SLUG_AND_DOMAIN = [ + 'shortCode' => 'custom-with-domain', + 'shortUrl' => 'http://some-domain.com/custom-with-domain', + 'longUrl' => 'https://google.com', + 'dateCreated' => '2018-10-20T00:00:00+00:00', + 'visitsCount' => 0, + 'tags' => [], + 'meta' => [ + 'validSince' => null, + 'validUntil' => null, + 'maxVisits' => null, + ], + 'originalUrl' => 'https://google.com', + ]; + private const SHORT_URL_META = [ + 'shortCode' => 'def456', + 'shortUrl' => 'http://doma.in/def456', + 'longUrl' => + 'https://blog.alejandrocelaya.com/2017/12/09' + . '/acmailer-7-0-the-most-important-release-in-a-long-time/', + 'dateCreated' => '2019-01-01T00:00:10+00:00', + 'visitsCount' => 2, + 'tags' => ['bar', 'foo'], + 'meta' => [ + 'validSince' => '2020-05-01T00:00:00+00:00', + 'validUntil' => null, + 'maxVisits' => null, + ], + 'originalUrl' => + 'https://blog.alejandrocelaya.com/2017/12/09' + . '/acmailer-7-0-the-most-important-release-in-a-long-time/', + ]; + private const SHORT_URL_CUSTOM_SLUG = [ + 'shortCode' => 'custom', + 'shortUrl' => 'http://doma.in/custom', + 'longUrl' => 'https://shlink.io', + 'dateCreated' => '2019-01-01T00:00:20+00:00', + 'visitsCount' => 0, + 'tags' => [], + 'meta' => [ + 'validSince' => null, + 'validUntil' => null, + 'maxVisits' => 2, + ], + 'originalUrl' => 'https://shlink.io', + ]; + private const SHORT_URL_CUSTOM_DOMAIN = [ + 'shortCode' => 'ghi789', + 'shortUrl' => 'http://example.com/ghi789', + 'longUrl' => + 'https://blog.alejandrocelaya.com/2019/04/27' + . '/considerations-to-properly-use-open-source-software-projects/', + 'dateCreated' => '2019-01-01T00:00:30+00:00', + 'visitsCount' => 0, + 'tags' => [], + 'meta' => [ + 'validSince' => null, + 'validUntil' => null, + 'maxVisits' => null, + ], + 'originalUrl' => + 'https://blog.alejandrocelaya.com/2019/04/27' + . '/considerations-to-properly-use-open-source-software-projects/', + ]; + + /** + * @test + * @dataProvider provideFilteredLists + */ + public function shortUrlsAreProperlyListed(array $query, array $expectedShortUrls): void { - $resp = $this->callApiWithKey(self::METHOD_GET, '/short-urls'); + $resp = $this->callApiWithKey(self::METHOD_GET, '/short-urls', [RequestOptions::QUERY => $query]); $respPayload = $this->getJsonResponsePayload($resp); $this->assertEquals(self::STATUS_OK, $resp->getStatusCode()); $this->assertEquals([ 'shortUrls' => [ - 'data' => [ - [ - 'shortCode' => 'abc123', - 'shortUrl' => 'http://doma.in/abc123', - 'longUrl' => 'https://shlink.io', - 'dateCreated' => '2019-01-01T00:00:00+00:00', - 'visitsCount' => 3, - 'tags' => ['foo'], - 'meta' => [ - 'validSince' => null, - 'validUntil' => null, - 'maxVisits' => null, - ], - 'originalUrl' => 'https://shlink.io', - ], - [ - 'shortCode' => 'def456', - 'shortUrl' => 'http://doma.in/def456', - 'longUrl' => - 'https://blog.alejandrocelaya.com/2017/12/09' - . '/acmailer-7-0-the-most-important-release-in-a-long-time/', - 'dateCreated' => '2019-01-01T00:00:00+00:00', - 'visitsCount' => 2, - 'tags' => ['bar', 'foo'], - 'meta' => [ - 'validSince' => '2020-05-01T00:00:00+00:00', - 'validUntil' => null, - 'maxVisits' => null, - ], - 'originalUrl' => - 'https://blog.alejandrocelaya.com/2017/12/09' - . '/acmailer-7-0-the-most-important-release-in-a-long-time/', - ], - [ - 'shortCode' => 'custom', - 'shortUrl' => 'http://doma.in/custom', - 'longUrl' => 'https://shlink.io', - 'dateCreated' => '2019-01-01T00:00:00+00:00', - 'visitsCount' => 0, - 'tags' => [], - 'meta' => [ - 'validSince' => null, - 'validUntil' => null, - 'maxVisits' => 2, - ], - 'originalUrl' => 'https://shlink.io', - ], - [ - 'shortCode' => 'ghi789', - 'shortUrl' => 'http://example.com/ghi789', - 'longUrl' => - 'https://blog.alejandrocelaya.com/2019/04/27' - . '/considerations-to-properly-use-open-source-software-projects/', - 'dateCreated' => '2019-01-01T00:00:00+00:00', - 'visitsCount' => 0, - 'tags' => [], - 'meta' => [ - 'validSince' => null, - 'validUntil' => null, - 'maxVisits' => null, - ], - 'originalUrl' => - 'https://blog.alejandrocelaya.com/2019/04/27' - . '/considerations-to-properly-use-open-source-software-projects/', - ], - [ - 'shortCode' => 'custom-with-domain', - 'shortUrl' => 'http://some-domain.com/custom-with-domain', - 'longUrl' => 'https://google.com', - 'dateCreated' => '2019-01-01T00:00:00+00:00', - 'visitsCount' => 0, - 'tags' => [], - 'meta' => [ - 'validSince' => null, - 'validUntil' => null, - 'maxVisits' => null, - ], - 'originalUrl' => 'https://google.com', - ], - ], - 'pagination' => [ - 'currentPage' => 1, - 'pagesCount' => 1, - 'itemsPerPage' => 10, - 'itemsInCurrentPage' => 5, - 'totalItems' => 5, - ], + 'data' => $expectedShortUrls, + 'pagination' => $this->buildPagination(count($expectedShortUrls)), ], ], $respPayload); } + + public function provideFilteredLists(): iterable + { + yield [[], [ + self::SHORT_URL_SHLINK, + self::SHORT_URL_CUSTOM_SLUG_AND_DOMAIN, + self::SHORT_URL_META, + self::SHORT_URL_CUSTOM_SLUG, + self::SHORT_URL_CUSTOM_DOMAIN, + ]]; + yield [['orderBy' => 'shortCode'], [ + self::SHORT_URL_SHLINK, + self::SHORT_URL_CUSTOM_SLUG, + self::SHORT_URL_CUSTOM_SLUG_AND_DOMAIN, + self::SHORT_URL_META, + self::SHORT_URL_CUSTOM_DOMAIN, + ]]; + yield [['startDate' => Chronos::parse('2018-12-01')->toAtomString()], [ + self::SHORT_URL_META, + self::SHORT_URL_CUSTOM_SLUG, + self::SHORT_URL_CUSTOM_DOMAIN, + ]]; + yield [['endDate' => Chronos::parse('2018-12-01')->toAtomString()], [ + self::SHORT_URL_SHLINK, + self::SHORT_URL_CUSTOM_SLUG_AND_DOMAIN, + ]]; + yield [['tags' => ['foo']], [ + self::SHORT_URL_SHLINK, + self::SHORT_URL_META, + ]]; + yield [['tags' => ['bar']], [ + self::SHORT_URL_META, + ]]; + yield [['tags' => ['foo'], 'endDate' => Chronos::parse('2018-12-01')->toAtomString()], [ + self::SHORT_URL_SHLINK, + ]]; + yield [['searchTerm' => 'alejandro'], [ + self::SHORT_URL_META, + self::SHORT_URL_CUSTOM_DOMAIN, + ]]; + } + + private function buildPagination(int $itemsCount): array + { + return [ + 'currentPage' => 1, + 'pagesCount' => 1, + 'itemsPerPage' => 10, + 'itemsInCurrentPage' => $itemsCount, + 'totalItems' => $itemsCount, + ]; + } } diff --git a/module/Rest/test-api/Action/ResolveShortUrlActionTest.php b/module/Rest/test-api/Action/ResolveShortUrlActionTest.php new file mode 100644 index 00000000..e4d45f4a --- /dev/null +++ b/module/Rest/test-api/Action/ResolveShortUrlActionTest.php @@ -0,0 +1,28 @@ +callApiWithKey(self::METHOD_GET, '/short-urls/invalid'); + $payload = $this->getJsonResponsePayload($resp); + + $this->assertEquals(self::STATUS_NOT_FOUND, $resp->getStatusCode()); + $this->assertEquals(self::STATUS_NOT_FOUND, $payload['status']); + $this->assertEquals('INVALID_SHORTCODE', $payload['type']); + $this->assertEquals('INVALID_SHORTCODE', $payload['error']); // Deprecated + $this->assertEquals($expectedDetail, $payload['detail']); + $this->assertEquals($expectedDetail, $payload['message']); // Deprecated + $this->assertEquals('Short URL not found', $payload['title']); + $this->assertEquals('invalid', $payload['shortCode']); + } +} diff --git a/module/Rest/test-api/Action/UpdateTagActionTest.php b/module/Rest/test-api/Action/UpdateTagActionTest.php index 206428af..fa07fcd1 100644 --- a/module/Rest/test-api/Action/UpdateTagActionTest.php +++ b/module/Rest/test-api/Action/UpdateTagActionTest.php @@ -9,9 +9,58 @@ use Shlinkio\Shlink\TestUtils\ApiTest\ApiTestCase; class UpdateTagActionTest extends ApiTestCase { + /** + * @test + * @dataProvider provideInvalidBody + */ + public function notProvidingTagsReturnsBadRequest(array $body): void + { + $expectedDetail = 'Provided data is not valid'; + + $resp = $this->callApiWithKey(self::METHOD_PUT, '/tags', [RequestOptions::JSON => $body]); + $payload = $this->getJsonResponsePayload($resp); + + $this->assertEquals(self::STATUS_BAD_REQUEST, $resp->getStatusCode()); + $this->assertEquals(self::STATUS_BAD_REQUEST, $payload['status']); + $this->assertEquals('INVALID_ARGUMENT', $payload['type']); + $this->assertEquals('INVALID_ARGUMENT', $payload['error']); // Deprecated + $this->assertEquals($expectedDetail, $payload['detail']); + $this->assertEquals($expectedDetail, $payload['message']); // Deprecated + $this->assertEquals('Invalid data', $payload['title']); + } + + public function provideInvalidBody(): iterable + { + yield [[]]; + yield [['oldName' => 'foo']]; + yield [['newName' => 'foo']]; + } + + /** @test */ + public function tryingToRenameInvalidTagReturnsNotFound(): void + { + $expectedDetail = 'Tag with name "invalid_tag" could not be found'; + + $resp = $this->callApiWithKey(self::METHOD_PUT, '/tags', [RequestOptions::JSON => [ + 'oldName' => 'invalid_tag', + 'newName' => 'foo', + ]]); + $payload = $this->getJsonResponsePayload($resp); + + $this->assertEquals(self::STATUS_NOT_FOUND, $resp->getStatusCode()); + $this->assertEquals(self::STATUS_NOT_FOUND, $payload['status']); + $this->assertEquals('TAG_NOT_FOUND', $payload['type']); + $this->assertEquals('TAG_NOT_FOUND', $payload['error']); // Deprecated + $this->assertEquals($expectedDetail, $payload['detail']); + $this->assertEquals($expectedDetail, $payload['message']); // Deprecated + $this->assertEquals('Tag not found', $payload['title']); + } + /** @test */ public function errorIsThrownWhenTryingToRenameTagToAnotherTagName(): void { + $expectedDetail = 'You cannot rename tag foo to bar, because it already exists'; + $resp = $this->callApiWithKey(self::METHOD_PUT, '/tags', [RequestOptions::JSON => [ 'oldName' => 'foo', 'newName' => 'bar', @@ -19,7 +68,12 @@ class UpdateTagActionTest extends ApiTestCase $payload = $this->getJsonResponsePayload($resp); $this->assertEquals(self::STATUS_CONFLICT, $resp->getStatusCode()); - $this->assertEquals('TAG_CONFLICT', $payload['error']); + $this->assertEquals(self::STATUS_CONFLICT, $payload['status']); + $this->assertEquals('TAG_CONFLICT', $payload['type']); + $this->assertEquals('TAG_CONFLICT', $payload['error']); // Deprecated + $this->assertEquals($expectedDetail, $payload['detail']); + $this->assertEquals($expectedDetail, $payload['message']); // Deprecated + $this->assertEquals('Tag conflict', $payload['title']); } /** @test */ diff --git a/module/Rest/test-api/Fixtures/ApiKeyFixture.php b/module/Rest/test-api/Fixtures/ApiKeyFixture.php index 2bc26187..971054fd 100644 --- a/module/Rest/test-api/Fixtures/ApiKeyFixture.php +++ b/module/Rest/test-api/Fixtures/ApiKeyFixture.php @@ -6,7 +6,7 @@ namespace ShlinkioApiTest\Shlink\Rest\Fixtures; use Cake\Chronos\Chronos; use Doctrine\Common\DataFixtures\FixtureInterface; -use Doctrine\Common\Persistence\ObjectManager; +use Doctrine\Persistence\ObjectManager; use ReflectionObject; use Shlinkio\Shlink\Rest\Entity\ApiKey; diff --git a/module/Rest/test-api/Fixtures/ShortUrlsFixture.php b/module/Rest/test-api/Fixtures/ShortUrlsFixture.php index 253b0032..cc359047 100644 --- a/module/Rest/test-api/Fixtures/ShortUrlsFixture.php +++ b/module/Rest/test-api/Fixtures/ShortUrlsFixture.php @@ -6,7 +6,7 @@ namespace ShlinkioApiTest\Shlink\Rest\Fixtures; use Cake\Chronos\Chronos; use Doctrine\Common\DataFixtures\AbstractFixture; -use Doctrine\Common\Persistence\ObjectManager; +use Doctrine\Persistence\ObjectManager; use ReflectionObject; use Shlinkio\Shlink\Core\Entity\ShortUrl; use Shlinkio\Shlink\Core\Model\ShortUrlMeta; @@ -21,32 +21,33 @@ class ShortUrlsFixture extends AbstractFixture public function load(ObjectManager $manager): void { $abcShortUrl = $this->setShortUrlDate( - new ShortUrl('https://shlink.io', ShortUrlMeta::createFromRawData(['customSlug' => 'abc123'])) + new ShortUrl('https://shlink.io', ShortUrlMeta::createFromRawData(['customSlug' => 'abc123'])), + '2018-05-01' ); $manager->persist($abcShortUrl); $defShortUrl = $this->setShortUrlDate(new ShortUrl( 'https://blog.alejandrocelaya.com/2017/12/09/acmailer-7-0-the-most-important-release-in-a-long-time/', ShortUrlMeta::createFromParams(Chronos::parse('2020-05-01'), null, 'def456') - )); + ), '2019-01-01 00:00:10'); $manager->persist($defShortUrl); $customShortUrl = $this->setShortUrlDate(new ShortUrl( 'https://shlink.io', ShortUrlMeta::createFromParams(null, null, 'custom', 2) - )); + ), '2019-01-01 00:00:20'); $manager->persist($customShortUrl); $withDomainShortUrl = $this->setShortUrlDate(new ShortUrl( 'https://blog.alejandrocelaya.com/2019/04/27/considerations-to-properly-use-open-source-software-projects/', ShortUrlMeta::createFromRawData(['domain' => 'example.com', 'customSlug' => 'ghi789']) - )); + ), '2019-01-01 00:00:30'); $manager->persist($withDomainShortUrl); $withDomainAndSlugShortUrl = $this->setShortUrlDate(new ShortUrl( 'https://google.com', ShortUrlMeta::createFromRawData(['domain' => 'some-domain.com', 'customSlug' => 'custom-with-domain']) - )); + ), '2018-10-20'); $manager->persist($withDomainAndSlugShortUrl); $manager->flush(); @@ -55,12 +56,12 @@ class ShortUrlsFixture extends AbstractFixture $this->addReference('def456_short_url', $defShortUrl); } - private function setShortUrlDate(ShortUrl $shortUrl): ShortUrl + private function setShortUrlDate(ShortUrl $shortUrl, string $date): ShortUrl { $ref = new ReflectionObject($shortUrl); $dateProp = $ref->getProperty('dateCreated'); $dateProp->setAccessible(true); - $dateProp->setValue($shortUrl, Chronos::create(2019, 1, 1, 0, 0, 0)); + $dateProp->setValue($shortUrl, Chronos::parse($date)); return $shortUrl; } diff --git a/module/Rest/test-api/Fixtures/TagsFixture.php b/module/Rest/test-api/Fixtures/TagsFixture.php index f498796b..5bd10ca7 100644 --- a/module/Rest/test-api/Fixtures/TagsFixture.php +++ b/module/Rest/test-api/Fixtures/TagsFixture.php @@ -7,7 +7,7 @@ namespace ShlinkioApiTest\Shlink\Rest\Fixtures; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\DependentFixtureInterface; -use Doctrine\Common\Persistence\ObjectManager; +use Doctrine\Persistence\ObjectManager; use Shlinkio\Shlink\Core\Entity\ShortUrl; use Shlinkio\Shlink\Core\Entity\Tag; diff --git a/module/Rest/test-api/Fixtures/VisitsFixture.php b/module/Rest/test-api/Fixtures/VisitsFixture.php index 9c1594a4..2c85c1a1 100644 --- a/module/Rest/test-api/Fixtures/VisitsFixture.php +++ b/module/Rest/test-api/Fixtures/VisitsFixture.php @@ -6,7 +6,7 @@ namespace ShlinkioApiTest\Shlink\Rest\Fixtures; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\DependentFixtureInterface; -use Doctrine\Common\Persistence\ObjectManager; +use Doctrine\Persistence\ObjectManager; use Shlinkio\Shlink\Core\Entity\ShortUrl; use Shlinkio\Shlink\Core\Entity\Visit; use Shlinkio\Shlink\Core\Model\Visitor; diff --git a/module/Rest/test-api/Middleware/AuthenticationTest.php b/module/Rest/test-api/Middleware/AuthenticationTest.php index 02836c85..d92f4a44 100644 --- a/module/Rest/test-api/Middleware/AuthenticationTest.php +++ b/module/Rest/test-api/Middleware/AuthenticationTest.php @@ -4,9 +4,8 @@ declare(strict_types=1); namespace ShlinkioApiTest\Shlink\Rest\Middleware; -use Shlinkio\Shlink\Rest\Authentication\Plugin\ApiKeyHeaderPlugin; +use Shlinkio\Shlink\Rest\Authentication\Plugin; use Shlinkio\Shlink\Rest\Authentication\RequestToHttpAuthPlugin; -use Shlinkio\Shlink\Rest\Util\RestUtils; use Shlinkio\Shlink\TestUtils\ApiTest\ApiTestCase; use function implode; @@ -17,18 +16,21 @@ class AuthenticationTest extends ApiTestCase /** @test */ public function authorizationErrorIsReturnedIfNoApiKeyIsSent(): void { + $expectedDetail = sprintf( + 'Expected one of the following authentication headers, ["%s"], but none were provided', + implode('", "', RequestToHttpAuthPlugin::SUPPORTED_AUTH_HEADERS) + ); + $resp = $this->callApi(self::METHOD_GET, '/short-codes'); - ['error' => $error, 'message' => $message] = $this->getJsonResponsePayload($resp); + $payload = $this->getJsonResponsePayload($resp); $this->assertEquals(self::STATUS_UNAUTHORIZED, $resp->getStatusCode()); - $this->assertEquals(RestUtils::INVALID_AUTHORIZATION_ERROR, $error); - $this->assertEquals( - sprintf( - 'Expected one of the following authentication headers, but none were provided, ["%s"]', - implode('", "', RequestToHttpAuthPlugin::SUPPORTED_AUTH_HEADERS) - ), - $message - ); + $this->assertEquals(self::STATUS_UNAUTHORIZED, $payload['status']); + $this->assertEquals('INVALID_AUTHORIZATION', $payload['type']); + $this->assertEquals('INVALID_AUTHORIZATION', $payload['error']); // Deprecated + $this->assertEquals($expectedDetail, $payload['detail']); + $this->assertEquals($expectedDetail, $payload['message']); // Deprecated + $this->assertEquals('Invalid authorization', $payload['title']); } /** @@ -37,16 +39,22 @@ class AuthenticationTest extends ApiTestCase */ public function apiKeyErrorIsReturnedWhenProvidedApiKeyIsInvalid(string $apiKey): void { + $expectedDetail = 'Provided API key does not exist or is invalid.'; + $resp = $this->callApi(self::METHOD_GET, '/short-codes', [ 'headers' => [ - ApiKeyHeaderPlugin::HEADER_NAME => $apiKey, + Plugin\ApiKeyHeaderPlugin::HEADER_NAME => $apiKey, ], ]); - ['error' => $error, 'message' => $message] = $this->getJsonResponsePayload($resp); + $payload = $this->getJsonResponsePayload($resp); $this->assertEquals(self::STATUS_UNAUTHORIZED, $resp->getStatusCode()); - $this->assertEquals(RestUtils::INVALID_API_KEY_ERROR, $error); - $this->assertEquals('Provided API key does not exist or is invalid.', $message); + $this->assertEquals(self::STATUS_UNAUTHORIZED, $payload['status']); + $this->assertEquals('INVALID_API_KEY', $payload['type']); + $this->assertEquals('INVALID_API_KEY', $payload['error']); // Deprecated + $this->assertEquals($expectedDetail, $payload['detail']); + $this->assertEquals($expectedDetail, $payload['message']); // Deprecated + $this->assertEquals('Invalid API key', $payload['title']); } public function provideInvalidApiKeys(): iterable @@ -55,4 +63,53 @@ class AuthenticationTest extends ApiTestCase yield 'key which is expired' => ['expired_api_key']; yield 'key which is disabled' => ['disabled_api_key']; } + + /** + * @test + * @dataProvider provideInvalidAuthorizations + */ + public function authorizationErrorIsReturnedIfInvalidDataIsProvided( + string $authValue, + string $expectedDetail, + string $expectedType, + string $expectedTitle + ): void { + $resp = $this->callApi(self::METHOD_GET, '/short-codes', [ + 'headers' => [ + Plugin\AuthorizationHeaderPlugin::HEADER_NAME => $authValue, + ], + ]); + $payload = $this->getJsonResponsePayload($resp); + + $this->assertEquals(self::STATUS_UNAUTHORIZED, $resp->getStatusCode()); + $this->assertEquals(self::STATUS_UNAUTHORIZED, $payload['status']); + $this->assertEquals($expectedType, $payload['type']); + $this->assertEquals($expectedType, $payload['error']); // Deprecated + $this->assertEquals($expectedDetail, $payload['detail']); + $this->assertEquals($expectedDetail, $payload['message']); // Deprecated + $this->assertEquals($expectedTitle, $payload['title']); + } + + public function provideInvalidAuthorizations(): iterable + { + yield 'no type' => [ + 'invalid', + 'You need to provide the Bearer type in the Authorization header.', + 'INVALID_AUTHORIZATION', + 'Invalid authorization', + ]; + yield 'invalid type' => [ + 'Basic invalid', + 'Provided authorization type Basic is not supported. Use Bearer instead.', + 'INVALID_AUTHORIZATION', + 'Invalid authorization', + ]; + yield 'invalid JWT' => [ + 'Bearer invalid', + 'Missing or invalid auth token provided. Perform a new authentication request and send provided ' + . 'token on every new request on the Authorization header', + 'INVALID_AUTH_TOKEN', + 'Invalid auth token', + ]; + } } diff --git a/module/Rest/test/Action/HealthActionFactoryTest.php b/module/Rest/test/Action/HealthActionFactoryTest.php deleted file mode 100644 index 3ecb15c1..00000000 --- a/module/Rest/test/Action/HealthActionFactoryTest.php +++ /dev/null @@ -1,44 +0,0 @@ -factory = new Action\HealthActionFactory(); - } - - /** @test */ - public function serviceIsCreatedExtractingConnectionFromEntityManager() - { - $em = $this->prophesize(EntityManager::class); - $conn = $this->prophesize(Connection::class); - - $getConnection = $em->getConnection()->willReturn($conn->reveal()); - - $sm = new ServiceManager(['services' => [ - 'Logger_Shlink' => $this->prophesize(LoggerInterface::class)->reveal(), - AppOptions::class => $this->prophesize(AppOptions::class)->reveal(), - EntityManager::class => $em->reveal(), - ]]); - - $instance = ($this->factory)($sm, ''); - - $this->assertInstanceOf(Action\HealthAction::class, $instance); - $getConnection->shouldHaveBeenCalledOnce(); - } -} diff --git a/module/Rest/test/Action/ShortUrl/CreateShortUrlActionTest.php b/module/Rest/test/Action/ShortUrl/CreateShortUrlActionTest.php index cea67f0f..37f737f9 100644 --- a/module/Rest/test/Action/ShortUrl/CreateShortUrlActionTest.php +++ b/module/Rest/test/Action/ShortUrl/CreateShortUrlActionTest.php @@ -4,19 +4,17 @@ declare(strict_types=1); namespace ShlinkioTest\Shlink\Rest\Action\ShortUrl; -use Exception; +use Cake\Chronos\Chronos; use PHPUnit\Framework\TestCase; use Prophecy\Argument; use Prophecy\Prophecy\ObjectProphecy; use Shlinkio\Shlink\Core\Entity\ShortUrl; -use Shlinkio\Shlink\Core\Exception\InvalidUrlException; -use Shlinkio\Shlink\Core\Exception\NonUniqueSlugException; +use Shlinkio\Shlink\Core\Exception\ValidationException; use Shlinkio\Shlink\Core\Model\ShortUrlMeta; use Shlinkio\Shlink\Core\Service\UrlShortener; use Shlinkio\Shlink\Rest\Action\ShortUrl\CreateShortUrlAction; -use Shlinkio\Shlink\Rest\Util\RestUtils; -use Zend\Diactoros\Response\JsonResponse; use Zend\Diactoros\ServerRequest; +use Zend\Diactoros\ServerRequestFactory; use Zend\Diactoros\Uri; use function strpos; @@ -42,39 +40,45 @@ class CreateShortUrlActionTest extends TestCase /** @test */ public function missingLongUrlParamReturnsError(): void { - $response = $this->action->handle(new ServerRequest()); - $this->assertEquals(400, $response->getStatusCode()); + $this->expectException(ValidationException::class); + $this->action->handle(new ServerRequest()); } - /** @test */ - public function properShortcodeConversionReturnsData(): void + /** + * @test + * @dataProvider provideRequestBodies + */ + public function properShortcodeConversionReturnsData(array $body, ShortUrlMeta $expectedMeta): void { $shortUrl = new ShortUrl(''); - $this->urlShortener->urlToShortCode(Argument::type(Uri::class), Argument::type('array'), Argument::cetera()) - ->willReturn($shortUrl) - ->shouldBeCalledOnce(); + $shorten = $this->urlShortener->urlToShortCode( + Argument::type(Uri::class), + Argument::type('array'), + $expectedMeta + )->willReturn($shortUrl); - $request = (new ServerRequest())->withParsedBody([ - 'longUrl' => 'http://www.domain.com/foo/bar', - ]); + $request = ServerRequestFactory::fromGlobals()->withParsedBody($body); $response = $this->action->handle($request); + $this->assertEquals(200, $response->getStatusCode()); $this->assertTrue(strpos($response->getBody()->getContents(), $shortUrl->toString(self::DOMAIN_CONFIG)) > 0); + $shorten->shouldHaveBeenCalledOnce(); } - /** @test */ - public function anInvalidUrlReturnsError(): void + public function provideRequestBodies(): iterable { - $this->urlShortener->urlToShortCode(Argument::type(Uri::class), Argument::type('array'), Argument::cetera()) - ->willThrow(InvalidUrlException::class) - ->shouldBeCalledOnce(); - - $request = (new ServerRequest())->withParsedBody([ + $fullMeta = [ 'longUrl' => 'http://www.domain.com/foo/bar', - ]); - $response = $this->action->handle($request); - $this->assertEquals(400, $response->getStatusCode()); - $this->assertTrue(strpos($response->getBody()->getContents(), RestUtils::INVALID_URL_ERROR) > 0); + 'validSince' => Chronos::now()->toAtomString(), + 'validUntil' => Chronos::now()->toAtomString(), + 'customSlug' => 'foo-bar-baz', + 'maxVisits' => 50, + 'findIfExists' => true, + 'domain' => 'my-domain.com', + ]; + + yield [['longUrl' => 'http://www.domain.com/foo/bar'], ShortUrlMeta::createEmpty()]; + yield [$fullMeta, ShortUrlMeta::createFromRawData($fullMeta)]; } /** @@ -90,13 +94,11 @@ class CreateShortUrlActionTest extends TestCase 'longUrl' => 'http://www.domain.com/foo/bar', 'domain' => $domain, ]); - /** @var JsonResponse $response */ - $response = $this->action->handle($request); - $payload = $response->getPayload(); - $this->assertEquals(400, $response->getStatusCode()); - $this->assertEquals(RestUtils::INVALID_ARGUMENT_ERROR, $payload['error']); - $urlToShortCode->shouldNotHaveBeenCalled(); + $this->expectException(ValidationException::class); + $urlToShortCode->shouldNotBeCalled(); + + $this->action->handle($request); } public function provideInvalidDomains(): iterable @@ -105,38 +107,4 @@ class CreateShortUrlActionTest extends TestCase yield ['127.0.0.1']; yield ['???/&%$&']; } - - /** @test */ - public function nonUniqueSlugReturnsError(): void - { - $this->urlShortener->urlToShortCode( - Argument::type(Uri::class), - Argument::type('array'), - ShortUrlMeta::createFromRawData(['customSlug' => 'foo']), - Argument::cetera() - )->willThrow(NonUniqueSlugException::class)->shouldBeCalledOnce(); - - $request = (new ServerRequest())->withParsedBody([ - 'longUrl' => 'http://www.domain.com/foo/bar', - 'customSlug' => 'foo', - ]); - $response = $this->action->handle($request); - $this->assertEquals(400, $response->getStatusCode()); - $this->assertStringContainsString(RestUtils::INVALID_SLUG_ERROR, (string) $response->getBody()); - } - - /** @test */ - public function aGenericExceptionWillReturnError(): void - { - $this->urlShortener->urlToShortCode(Argument::type(Uri::class), Argument::type('array'), Argument::cetera()) - ->willThrow(Exception::class) - ->shouldBeCalledOnce(); - - $request = (new ServerRequest())->withParsedBody([ - 'longUrl' => 'http://www.domain.com/foo/bar', - ]); - $response = $this->action->handle($request); - $this->assertEquals(500, $response->getStatusCode()); - $this->assertTrue(strpos($response->getBody()->getContents(), RestUtils::UNKNOWN_ERROR) > 0); - } } diff --git a/module/Rest/test/Action/ShortUrl/DeleteShortUrlActionTest.php b/module/Rest/test/Action/ShortUrl/DeleteShortUrlActionTest.php index 35f87dc8..782181ce 100644 --- a/module/Rest/test/Action/ShortUrl/DeleteShortUrlActionTest.php +++ b/module/Rest/test/Action/ShortUrl/DeleteShortUrlActionTest.php @@ -7,12 +7,8 @@ namespace ShlinkioTest\Shlink\Rest\Action\ShortUrl; use PHPUnit\Framework\TestCase; use Prophecy\Argument; use Prophecy\Prophecy\ObjectProphecy; -use Shlinkio\Shlink\Core\Exception; use Shlinkio\Shlink\Core\Service\ShortUrl\DeleteShortUrlServiceInterface; use Shlinkio\Shlink\Rest\Action\ShortUrl\DeleteShortUrlAction; -use Shlinkio\Shlink\Rest\Util\RestUtils; -use Throwable; -use Zend\Diactoros\Response\JsonResponse; use Zend\Diactoros\ServerRequest; class DeleteShortUrlActionTest extends TestCase @@ -39,31 +35,4 @@ class DeleteShortUrlActionTest extends TestCase $this->assertEquals(204, $resp->getStatusCode()); $deleteByShortCode->shouldHaveBeenCalledOnce(); } - - /** - * @test - * @dataProvider provideExceptions - */ - public function returnsErrorResponseInCaseOfException(Throwable $e, string $error, int $statusCode): void - { - $deleteByShortCode = $this->service->deleteByShortCode(Argument::any())->willThrow($e); - - /** @var JsonResponse $resp */ - $resp = $this->action->handle(new ServerRequest()); - $payload = $resp->getPayload(); - - $this->assertEquals($statusCode, $resp->getStatusCode()); - $this->assertEquals($error, $payload['error']); - $deleteByShortCode->shouldHaveBeenCalledOnce(); - } - - public function provideExceptions(): iterable - { - yield 'not found' => [new Exception\InvalidShortCodeException(), RestUtils::INVALID_SHORTCODE_ERROR, 404]; - yield 'bad request' => [ - new Exception\DeleteShortUrlException(5), - RestUtils::INVALID_SHORTCODE_DELETION_ERROR, - 400, - ]; - } } diff --git a/module/Rest/test/Action/ShortUrl/EditShortUrlActionTest.php b/module/Rest/test/Action/ShortUrl/EditShortUrlActionTest.php index d8e62c20..ff86117e 100644 --- a/module/Rest/test/Action/ShortUrl/EditShortUrlActionTest.php +++ b/module/Rest/test/Action/ShortUrl/EditShortUrlActionTest.php @@ -8,11 +8,9 @@ use PHPUnit\Framework\TestCase; use Prophecy\Argument; use Prophecy\Prophecy\ObjectProphecy; use Shlinkio\Shlink\Core\Entity\ShortUrl; -use Shlinkio\Shlink\Core\Exception\InvalidShortCodeException; +use Shlinkio\Shlink\Core\Exception\ValidationException; use Shlinkio\Shlink\Core\Service\ShortUrlServiceInterface; use Shlinkio\Shlink\Rest\Action\ShortUrl\EditShortUrlAction; -use Shlinkio\Shlink\Rest\Util\RestUtils; -use Zend\Diactoros\Response\JsonResponse; use Zend\Diactoros\ServerRequest; class EditShortUrlActionTest extends TestCase @@ -29,44 +27,19 @@ class EditShortUrlActionTest extends TestCase } /** @test */ - public function invalidDataReturnsError() + public function invalidDataThrowsError(): void { $request = (new ServerRequest())->withParsedBody([ 'maxVisits' => 'invalid', ]); - /** @var JsonResponse $resp */ - $resp = $this->action->handle($request); - $payload = $resp->getPayload(); + $this->expectException(ValidationException::class); - $this->assertEquals(400, $resp->getStatusCode()); - $this->assertEquals(RestUtils::INVALID_ARGUMENT_ERROR, $payload['error']); - $this->assertEquals('Provided data is invalid.', $payload['message']); + $this->action->handle($request); } /** @test */ - public function incorrectShortCodeReturnsError() - { - $request = (new ServerRequest())->withAttribute('shortCode', 'abc123') - ->withParsedBody([ - 'maxVisits' => 5, - ]); - $updateMeta = $this->shortUrlService->updateMetadataByShortCode(Argument::cetera())->willThrow( - InvalidShortCodeException::class - ); - - /** @var JsonResponse $resp */ - $resp = $this->action->handle($request); - $payload = $resp->getPayload(); - - $this->assertEquals(404, $resp->getStatusCode()); - $this->assertEquals(RestUtils::INVALID_SHORTCODE_ERROR, $payload['error']); - $this->assertEquals('No URL found for short code "abc123"', $payload['message']); - $updateMeta->shouldHaveBeenCalled(); - } - - /** @test */ - public function correctShortCodeReturnsSuccess() + public function correctShortCodeReturnsSuccess(): void { $request = (new ServerRequest())->withAttribute('shortCode', 'abc123') ->withParsedBody([ diff --git a/module/Rest/test/Action/ShortUrl/EditShortUrlTagsActionTest.php b/module/Rest/test/Action/ShortUrl/EditShortUrlTagsActionTest.php index d56bbaf1..17293f05 100644 --- a/module/Rest/test/Action/ShortUrl/EditShortUrlTagsActionTest.php +++ b/module/Rest/test/Action/ShortUrl/EditShortUrlTagsActionTest.php @@ -7,7 +7,7 @@ namespace ShlinkioTest\Shlink\Rest\Action\ShortUrl; use PHPUnit\Framework\TestCase; use Prophecy\Prophecy\ObjectProphecy; use Shlinkio\Shlink\Core\Entity\ShortUrl; -use Shlinkio\Shlink\Core\Exception\InvalidShortCodeException; +use Shlinkio\Shlink\Core\Exception\ValidationException; use Shlinkio\Shlink\Core\Service\ShortUrlService; use Shlinkio\Shlink\Rest\Action\ShortUrl\EditShortUrlTagsAction; use Zend\Diactoros\ServerRequest; @@ -26,28 +26,14 @@ class EditShortUrlTagsActionTest extends TestCase } /** @test */ - public function notProvidingTagsReturnsError() + public function notProvidingTagsReturnsError(): void { - $response = $this->action->handle((new ServerRequest())->withAttribute('shortCode', 'abc123')); - $this->assertEquals(400, $response->getStatusCode()); + $this->expectException(ValidationException::class); + $this->action->handle((new ServerRequest())->withAttribute('shortCode', 'abc123')); } /** @test */ - public function anInvalidShortCodeReturnsNotFound() - { - $shortCode = 'abc123'; - $this->shortUrlService->setTagsByShortCode($shortCode, [])->willThrow(InvalidShortCodeException::class) - ->shouldBeCalledOnce(); - - $response = $this->action->handle( - (new ServerRequest())->withAttribute('shortCode', 'abc123') - ->withParsedBody(['tags' => []]) - ); - $this->assertEquals(404, $response->getStatusCode()); - } - - /** @test */ - public function tagsListIsReturnedIfCorrectShortCodeIsProvided() + public function tagsListIsReturnedIfCorrectShortCodeIsProvided(): void { $shortCode = 'abc123'; $this->shortUrlService->setTagsByShortCode($shortCode, [])->willReturn(new ShortUrl('')) diff --git a/module/Rest/test/Action/ShortUrl/ListShortUrlsActionTest.php b/module/Rest/test/Action/ShortUrl/ListShortUrlsActionTest.php index 7bb2d623..1dfdc258 100644 --- a/module/Rest/test/Action/ShortUrl/ListShortUrlsActionTest.php +++ b/module/Rest/test/Action/ShortUrl/ListShortUrlsActionTest.php @@ -4,10 +4,11 @@ declare(strict_types=1); namespace ShlinkioTest\Shlink\Rest\Action\ShortUrl; -use Exception; +use Cake\Chronos\Chronos; use PHPUnit\Framework\TestCase; use Prophecy\Prophecy\ObjectProphecy; use Psr\Log\LoggerInterface; +use Shlinkio\Shlink\Common\Util\DateRange; use Shlinkio\Shlink\Core\Service\ShortUrlService; use Shlinkio\Shlink\Rest\Action\ShortUrl\ListShortUrlsAction; use Zend\Diactoros\Response\JsonResponse; @@ -44,13 +45,15 @@ class ListShortUrlsActionTest extends TestCase int $expectedPage, ?string $expectedSearchTerm, array $expectedTags, - ?string $expectedOrderBy + ?string $expectedOrderBy, + DateRange $expectedDateRange ): void { $listShortUrls = $this->service->listShortUrls( $expectedPage, $expectedSearchTerm, $expectedTags, - $expectedOrderBy + $expectedOrderBy, + $expectedDateRange )->willReturn(new Paginator(new ArrayAdapter())); /** @var JsonResponse $response */ @@ -66,39 +69,44 @@ class ListShortUrlsActionTest extends TestCase public function provideFilteringData(): iterable { - yield [[], 1, null, [], null]; - yield [['page' => 10], 10, null, [], null]; - yield [['page' => null], 1, null, [], null]; - yield [['page' => '8'], 8, null, [], null]; - yield [['searchTerm' => $searchTerm = 'foo'], 1, $searchTerm, [], null]; - yield [['tags' => $tags = ['foo','bar']], 1, null, $tags, null]; - yield [['orderBy' => $orderBy = 'something'], 1, null, [], $orderBy]; + yield [[], 1, null, [], null, new DateRange()]; + yield [['page' => 10], 10, null, [], null, new DateRange()]; + yield [['page' => null], 1, null, [], null, new DateRange()]; + yield [['page' => '8'], 8, null, [], null, new DateRange()]; + yield [['searchTerm' => $searchTerm = 'foo'], 1, $searchTerm, [], null, new DateRange()]; + yield [['tags' => $tags = ['foo','bar']], 1, null, $tags, null, new DateRange()]; + yield [['orderBy' => $orderBy = 'something'], 1, null, [], $orderBy, new DateRange()]; yield [[ 'page' => '2', 'orderBy' => $orderBy = 'something', 'tags' => $tags = ['one', 'two'], - ], 2, null, $tags, $orderBy]; - } - - /** @test */ - public function anExceptionReturnsErrorResponse(): void - { - $page = 3; - $e = new Exception(); - - $this->service->listShortUrls($page, null, [], null)->willThrow($e) - ->shouldBeCalledOnce(); - $logError = $this->logger->error( - 'Unexpected error while listing short URLs. {e}', - ['e' => $e] - )->will(function () { - }); - - $response = $this->action->handle((new ServerRequest())->withQueryParams([ - 'page' => $page, - ])); - - $this->assertEquals(500, $response->getStatusCode()); - $logError->shouldHaveBeenCalledOnce(); + ], 2, null, $tags, $orderBy, new DateRange()]; + yield [ + ['startDate' => $date = Chronos::now()->toAtomString()], + 1, + null, + [], + null, + new DateRange(Chronos::parse($date)), + ]; + yield [ + ['endDate' => $date = Chronos::now()->toAtomString()], + 1, + null, + [], + null, + new DateRange(null, Chronos::parse($date)), + ]; + yield [ + [ + 'startDate' => $startDate = Chronos::now()->subDays(10)->toAtomString(), + 'endDate' => $endDate = Chronos::now()->toAtomString(), + ], + 1, + null, + [], + null, + new DateRange(Chronos::parse($startDate), Chronos::parse($endDate)), + ]; } } diff --git a/module/Rest/test/Action/ShortUrl/ResolveShortUrlActionTest.php b/module/Rest/test/Action/ShortUrl/ResolveShortUrlActionTest.php index e0c23d31..b77a6e45 100644 --- a/module/Rest/test/Action/ShortUrl/ResolveShortUrlActionTest.php +++ b/module/Rest/test/Action/ShortUrl/ResolveShortUrlActionTest.php @@ -4,15 +4,11 @@ declare(strict_types=1); namespace ShlinkioTest\Shlink\Rest\Action\ShortUrl; -use Exception; use PHPUnit\Framework\TestCase; use Prophecy\Prophecy\ObjectProphecy; use Shlinkio\Shlink\Core\Entity\ShortUrl; -use Shlinkio\Shlink\Core\Exception\EntityDoesNotExistException; -use Shlinkio\Shlink\Core\Exception\InvalidShortCodeException; use Shlinkio\Shlink\Core\Service\UrlShortener; use Shlinkio\Shlink\Rest\Action\ShortUrl\ResolveShortUrlAction; -use Shlinkio\Shlink\Rest\Util\RestUtils; use Zend\Diactoros\ServerRequest; use function strpos; @@ -30,19 +26,6 @@ class ResolveShortUrlActionTest extends TestCase $this->action = new ResolveShortUrlAction($this->urlShortener->reveal(), []); } - /** @test */ - public function incorrectShortCodeReturnsError(): void - { - $shortCode = 'abc123'; - $this->urlShortener->shortCodeToUrl($shortCode, null)->willThrow(EntityDoesNotExistException::class) - ->shouldBeCalledOnce(); - - $request = (new ServerRequest())->withAttribute('shortCode', $shortCode); - $response = $this->action->handle($request); - $this->assertEquals(404, $response->getStatusCode()); - $this->assertTrue(strpos($response->getBody()->getContents(), RestUtils::INVALID_ARGUMENT_ERROR) > 0); - } - /** @test */ public function correctShortCodeReturnsSuccess(): void { @@ -56,30 +39,4 @@ class ResolveShortUrlActionTest extends TestCase $this->assertEquals(200, $response->getStatusCode()); $this->assertTrue(strpos($response->getBody()->getContents(), 'http://domain.com/foo/bar') > 0); } - - /** @test */ - public function invalidShortCodeExceptionReturnsError(): void - { - $shortCode = 'abc123'; - $this->urlShortener->shortCodeToUrl($shortCode, null)->willThrow(InvalidShortCodeException::class) - ->shouldBeCalledOnce(); - - $request = (new ServerRequest())->withAttribute('shortCode', $shortCode); - $response = $this->action->handle($request); - $this->assertEquals(400, $response->getStatusCode()); - $this->assertTrue(strpos($response->getBody()->getContents(), RestUtils::INVALID_SHORTCODE_ERROR) > 0); - } - - /** @test */ - public function unexpectedExceptionWillReturnError(): void - { - $shortCode = 'abc123'; - $this->urlShortener->shortCodeToUrl($shortCode, null)->willThrow(Exception::class) - ->shouldBeCalledOnce(); - - $request = (new ServerRequest())->withAttribute('shortCode', $shortCode); - $response = $this->action->handle($request); - $this->assertEquals(500, $response->getStatusCode()); - $this->assertTrue(strpos($response->getBody()->getContents(), RestUtils::UNKNOWN_ERROR) > 0); - } } diff --git a/module/Rest/test/Action/ShortUrl/SingleStepCreateShortUrlActionTest.php b/module/Rest/test/Action/ShortUrl/SingleStepCreateShortUrlActionTest.php index f3452e9a..b0d8c65d 100644 --- a/module/Rest/test/Action/ShortUrl/SingleStepCreateShortUrlActionTest.php +++ b/module/Rest/test/Action/ShortUrl/SingleStepCreateShortUrlActionTest.php @@ -10,11 +10,11 @@ use Prophecy\Argument; use Prophecy\Prophecy\ObjectProphecy; use Psr\Http\Message\UriInterface; use Shlinkio\Shlink\Core\Entity\ShortUrl; +use Shlinkio\Shlink\Core\Exception\ValidationException; use Shlinkio\Shlink\Core\Model\ShortUrlMeta; use Shlinkio\Shlink\Core\Service\UrlShortenerInterface; use Shlinkio\Shlink\Rest\Action\ShortUrl\SingleStepCreateShortUrlAction; use Shlinkio\Shlink\Rest\Service\ApiKeyServiceInterface; -use Zend\Diactoros\Response\JsonResponse; use Zend\Diactoros\ServerRequest; class SingleStepCreateShortUrlActionTest extends TestCase @@ -42,39 +42,31 @@ class SingleStepCreateShortUrlActionTest extends TestCase } /** @test */ - public function errorResponseIsReturnedIfInvalidApiKeyIsProvided() + public function errorResponseIsReturnedIfInvalidApiKeyIsProvided(): void { $request = (new ServerRequest())->withQueryParams(['apiKey' => 'abc123']); $findApiKey = $this->apiKeyService->check('abc123')->willReturn(false); - /** @var JsonResponse $resp */ - $resp = $this->action->handle($request); - $payload = $resp->getPayload(); + $this->expectException(ValidationException::class); + $findApiKey->shouldBeCalledOnce(); - $this->assertEquals(400, $resp->getStatusCode()); - $this->assertEquals('INVALID_ARGUMENT', $payload['error']); - $this->assertEquals('No API key was provided or it is not valid', $payload['message']); - $findApiKey->shouldHaveBeenCalled(); + $this->action->handle($request); } /** @test */ - public function errorResponseIsReturnedIfNoUrlIsProvided() + public function errorResponseIsReturnedIfNoUrlIsProvided(): void { $request = (new ServerRequest())->withQueryParams(['apiKey' => 'abc123']); $findApiKey = $this->apiKeyService->check('abc123')->willReturn(true); - /** @var JsonResponse $resp */ - $resp = $this->action->handle($request); - $payload = $resp->getPayload(); + $this->expectException(ValidationException::class); + $findApiKey->shouldBeCalledOnce(); - $this->assertEquals(400, $resp->getStatusCode()); - $this->assertEquals('INVALID_ARGUMENT', $payload['error']); - $this->assertEquals('A URL was not provided', $payload['message']); - $findApiKey->shouldHaveBeenCalled(); + $this->action->handle($request); } /** @test */ - public function properDataIsPassedWhenGeneratingShortCode() + public function properDataIsPassedWhenGeneratingShortCode(): void { $request = (new ServerRequest())->withQueryParams([ 'apiKey' => 'abc123', diff --git a/module/Rest/test/Action/Tag/UpdateTagActionTest.php b/module/Rest/test/Action/Tag/UpdateTagActionTest.php index 9ded1716..3b068add 100644 --- a/module/Rest/test/Action/Tag/UpdateTagActionTest.php +++ b/module/Rest/test/Action/Tag/UpdateTagActionTest.php @@ -7,7 +7,7 @@ namespace ShlinkioTest\Shlink\Rest\Action\Tag; use PHPUnit\Framework\TestCase; use Prophecy\Prophecy\ObjectProphecy; use Shlinkio\Shlink\Core\Entity\Tag; -use Shlinkio\Shlink\Core\Exception\EntityDoesNotExistException; +use Shlinkio\Shlink\Core\Exception\ValidationException; use Shlinkio\Shlink\Core\Service\Tag\TagServiceInterface; use Shlinkio\Shlink\Rest\Action\Tag\UpdateTagAction; use Zend\Diactoros\ServerRequest; @@ -32,9 +32,10 @@ class UpdateTagActionTest extends TestCase public function whenInvalidParamsAreProvidedAnErrorIsReturned(array $bodyParams): void { $request = (new ServerRequest())->withParsedBody($bodyParams); - $resp = $this->action->handle($request); - $this->assertEquals(400, $resp->getStatusCode()); + $this->expectException(ValidationException::class); + + $this->action->handle($request); } public function provideParams(): iterable @@ -44,21 +45,6 @@ class UpdateTagActionTest extends TestCase yield 'no params' => [[]]; } - /** @test */ - public function requestingInvalidTagReturnsError(): void - { - $request = (new ServerRequest())->withParsedBody([ - 'oldName' => 'foo', - 'newName' => 'bar', - ]); - $rename = $this->tagService->renameTag('foo', 'bar')->willThrow(EntityDoesNotExistException::class); - - $resp = $this->action->handle($request); - - $this->assertEquals(404, $resp->getStatusCode()); - $rename->shouldHaveBeenCalled(); - } - /** @test */ public function correctInvocationRenamesTag(): void { diff --git a/module/Rest/test/Action/Visit/GetVisitsActionTest.php b/module/Rest/test/Action/Visit/GetVisitsActionTest.php index 6a4b533c..80e06085 100644 --- a/module/Rest/test/Action/Visit/GetVisitsActionTest.php +++ b/module/Rest/test/Action/Visit/GetVisitsActionTest.php @@ -8,7 +8,6 @@ use Cake\Chronos\Chronos; use PHPUnit\Framework\TestCase; use Prophecy\Argument; use Prophecy\Prophecy\ObjectProphecy; -use Shlinkio\Shlink\Common\Exception\InvalidArgumentException; use Shlinkio\Shlink\Common\Util\DateRange; use Shlinkio\Shlink\Core\Model\VisitsParams; use Shlinkio\Shlink\Core\Service\VisitsTracker; @@ -31,7 +30,7 @@ class GetVisitsActionTest extends TestCase } /** @test */ - public function providingCorrectShortCodeReturnsVisits() + public function providingCorrectShortCodeReturnsVisits(): void { $shortCode = 'abc123'; $this->visitsTracker->info($shortCode, Argument::type(VisitsParams::class))->willReturn( @@ -43,19 +42,7 @@ class GetVisitsActionTest extends TestCase } /** @test */ - public function providingInvalidShortCodeReturnsError() - { - $shortCode = 'abc123'; - $this->visitsTracker->info($shortCode, Argument::type(VisitsParams::class))->willThrow( - InvalidArgumentException::class - )->shouldBeCalledOnce(); - - $response = $this->action->handle((new ServerRequest())->withAttribute('shortCode', $shortCode)); - $this->assertEquals(404, $response->getStatusCode()); - } - - /** @test */ - public function paramsAreReadFromQuery() + public function paramsAreReadFromQuery(): void { $shortCode = 'abc123'; $this->visitsTracker->info($shortCode, new VisitsParams( diff --git a/module/Rest/test/Authentication/RequestToAuthPluginTest.php b/module/Rest/test/Authentication/RequestToAuthPluginTest.php index e9d68489..a49a4e19 100644 --- a/module/Rest/test/Authentication/RequestToAuthPluginTest.php +++ b/module/Rest/test/Authentication/RequestToAuthPluginTest.php @@ -11,7 +11,7 @@ use Shlinkio\Shlink\Rest\Authentication\Plugin\ApiKeyHeaderPlugin; use Shlinkio\Shlink\Rest\Authentication\Plugin\AuthenticationPluginInterface; use Shlinkio\Shlink\Rest\Authentication\Plugin\AuthorizationHeaderPlugin; use Shlinkio\Shlink\Rest\Authentication\RequestToHttpAuthPlugin; -use Shlinkio\Shlink\Rest\Exception\NoAuthenticationException; +use Shlinkio\Shlink\Rest\Exception\MissingAuthenticationException; use Zend\Diactoros\ServerRequest; use function implode; @@ -35,9 +35,9 @@ class RequestToAuthPluginTest extends TestCase { $request = new ServerRequest(); - $this->expectException(NoAuthenticationException::class); + $this->expectException(MissingAuthenticationException::class); $this->expectExceptionMessage(sprintf( - 'None of the valid authentication mechanisms where provided. Expected one of ["%s"]', + 'Expected one of the following authentication headers, ["%s"], but none were provided', implode('", "', RequestToHttpAuthPlugin::SUPPORTED_AUTH_HEADERS) )); diff --git a/module/Rest/test/ConfigProviderTest.php b/module/Rest/test/ConfigProviderTest.php index 57959367..2922faad 100644 --- a/module/Rest/test/ConfigProviderTest.php +++ b/module/Rest/test/ConfigProviderTest.php @@ -18,12 +18,33 @@ class ConfigProviderTest extends TestCase } /** @test */ - public function properConfigIsReturned() + public function properConfigIsReturned(): void { - $config = $this->configProvider->__invoke(); + $config = ($this->configProvider)(); - $this->assertArrayHasKey('error_handler', $config); $this->assertArrayHasKey('routes', $config); $this->assertArrayHasKey('dependencies', $config); } + + /** @test */ + public function routesAreProperlyPrefixed(): void + { + $configProvider = new ConfigProvider(function () { + return [ + 'routes' => [ + ['path' => '/foo'], + ['path' => '/bar'], + ['path' => '/baz/foo'], + ], + ]; + }); + + $config = $configProvider(); + + $this->assertEquals([ + ['path' => '/rest/v{version:1|2}/foo'], + ['path' => '/rest/v{version:1|2}/bar'], + ['path' => '/rest/v{version:1|2}/baz/foo'], + ], $config['routes']); + } } diff --git a/module/Rest/test/ErrorHandler/JsonErrorResponseGeneratorTest.php b/module/Rest/test/ErrorHandler/JsonErrorResponseGeneratorTest.php deleted file mode 100644 index d9b99bdd..00000000 --- a/module/Rest/test/ErrorHandler/JsonErrorResponseGeneratorTest.php +++ /dev/null @@ -1,62 +0,0 @@ -errorHandler = new JsonErrorResponseGenerator(); - } - - /** @test */ - public function noErrorStatusReturnsInternalServerError(): void - { - /** @var Response\JsonResponse $response */ - $response = $this->errorHandler->__invoke(null, new ServerRequest(), new Response()); - $payload = $response->getPayload(); - - $this->assertInstanceOf(Response\JsonResponse::class, $response); - $this->assertEquals(500, $response->getStatusCode()); - $this->assertEquals('Internal Server Error', $payload['message']); - } - - /** - * @test - * @dataProvider provideStatus - */ - public function errorStatusReturnsThatStatus(int $status, string $message): void - { - /** @var Response\JsonResponse $response */ - $response = $this->errorHandler->__invoke( - null, - new ServerRequest(), - (new Response())->withStatus($status, $message) - ); - $payload = $response->getPayload(); - - $this->assertInstanceOf(Response\JsonResponse::class, $response); - $this->assertEquals($status, $response->getStatusCode()); - $this->assertEquals($message, $payload['message']); - } - - public function provideStatus(): iterable - { - return array_map(function (int $status) { - return [$status, 'Some message']; - }, range(400, 500, 20)); - } -} diff --git a/module/Rest/test/EventDispatcher/NotifyVisitToWebHooksTest.php b/module/Rest/test/EventDispatcher/NotifyVisitToWebHooksTest.php new file mode 100644 index 00000000..305f2e23 --- /dev/null +++ b/module/Rest/test/EventDispatcher/NotifyVisitToWebHooksTest.php @@ -0,0 +1,132 @@ +httpClient = $this->prophesize(ClientInterface::class); + $this->em = $this->prophesize(EntityManagerInterface::class); + $this->logger = $this->prophesize(LoggerInterface::class); + } + + /** @test */ + public function emptyWebhooksMakeNoFurtherActions(): void + { + $find = $this->em->find(Visit::class, '1')->willReturn(null); + + $this->createListener([])(new VisitLocated('1')); + + $find->shouldNotHaveBeenCalled(); + } + + /** @test */ + public function invalidVisitDoesNotPerformAnyRequest(): void + { + $find = $this->em->find(Visit::class, '1')->willReturn(null); + $requestAsync = $this->httpClient->requestAsync( + RequestMethodInterface::METHOD_POST, + Argument::type('string'), + Argument::type('array') + )->willReturn(new FulfilledPromise('')); + $logWarning = $this->logger->warning( + 'Tried to notify webhooks for visit with id "{visitId}", but it does not exist.', + ['visitId' => '1'] + ); + + $this->createListener(['foo', 'bar'])(new VisitLocated('1')); + + $find->shouldHaveBeenCalledOnce(); + $logWarning->shouldHaveBeenCalledOnce(); + $requestAsync->shouldNotHaveBeenCalled(); + } + + /** @test */ + public function expectedRequestsArePerformedToWebhooks(): void + { + $webhooks = ['foo', 'invalid', 'bar', 'baz']; + $invalidWebhooks = ['invalid', 'baz']; + + $find = $this->em->find(Visit::class, '1')->willReturn(new Visit(new ShortUrl(''), Visitor::emptyInstance())); + $requestAsync = $this->httpClient->requestAsync( + RequestMethodInterface::METHOD_POST, + Argument::type('string'), + Argument::that(function (array $requestOptions) { + Assert::assertArrayHasKey(RequestOptions::HEADERS, $requestOptions); + Assert::assertArrayHasKey(RequestOptions::JSON, $requestOptions); + Assert::assertArrayHasKey(RequestOptions::TIMEOUT, $requestOptions); + Assert::assertEquals($requestOptions[RequestOptions::TIMEOUT], 10); + Assert::assertEquals($requestOptions[RequestOptions::HEADERS], ['User-Agent' => 'Shlink:v1.2.3']); + Assert::assertArrayHasKey('shortUrl', $requestOptions[RequestOptions::JSON]); + Assert::assertArrayHasKey('visit', $requestOptions[RequestOptions::JSON]); + + return $requestOptions; + }) + )->will(function (array $args) use ($invalidWebhooks) { + [, $webhook] = $args; + $e = new Exception(''); + + return contains($invalidWebhooks, $webhook) ? new RejectedPromise($e) : new FulfilledPromise(''); + }); + $logWarning = $this->logger->warning( + 'Failed to notify visit with id "{visitId}" to webhook "{webhook}". {e}', + Argument::that(function (array $extra) { + Assert::assertArrayHasKey('webhook', $extra); + Assert::assertArrayHasKey('visitId', $extra); + Assert::assertArrayHasKey('e', $extra); + + return $extra; + }) + ); + + $this->createListener($webhooks)(new VisitLocated('1')); + + $find->shouldHaveBeenCalledOnce(); + $requestAsync->shouldHaveBeenCalledTimes(count($webhooks)); + $logWarning->shouldHaveBeenCalledTimes(count($invalidWebhooks)); + } + + private function createListener(array $webhooks): NotifyVisitToWebHooks + { + return new NotifyVisitToWebHooks( + $this->httpClient->reveal(), + $this->em->reveal(), + $this->logger->reveal(), + $webhooks, + [], + new AppOptions(['name' => 'Shlink', 'version' => '1.2.3']) + ); + } +} diff --git a/module/Rest/test/Exception/MissingAuthenticationExceptionTest.php b/module/Rest/test/Exception/MissingAuthenticationExceptionTest.php new file mode 100644 index 00000000..84c72e75 --- /dev/null +++ b/module/Rest/test/Exception/MissingAuthenticationExceptionTest.php @@ -0,0 +1,43 @@ +assertEquals($expectedMessage, $e->getMessage()); + $this->assertEquals($expectedMessage, $e->getDetail()); + $this->assertEquals('Invalid authorization', $e->getTitle()); + $this->assertEquals('INVALID_AUTHORIZATION', $e->getType()); + $this->assertEquals(401, $e->getStatus()); + $this->assertEquals(['expectedTypes' => $expectedTypes], $e->getAdditionalData()); + } + + public function provideExpectedTypes(): iterable + { + yield [['foo', 'bar']]; + yield [['something']]; + yield [[]]; + yield [['foo', 'bar', 'baz']]; + } +} diff --git a/module/Rest/test/Exception/VerifyAuthenticationExceptionTest.php b/module/Rest/test/Exception/VerifyAuthenticationExceptionTest.php index d19fe0f6..28563c5f 100644 --- a/module/Rest/test/Exception/VerifyAuthenticationExceptionTest.php +++ b/module/Rest/test/Exception/VerifyAuthenticationExceptionTest.php @@ -4,92 +4,16 @@ declare(strict_types=1); namespace ShlinkioTest\Shlink\Rest\Exception; -use Exception; use PHPUnit\Framework\TestCase; -use Shlinkio\Shlink\Common\Util\StringUtilsTrait; use Shlinkio\Shlink\Rest\Exception\VerifyAuthenticationException; -use Throwable; - -use function array_map; -use function random_int; -use function range; -use function sprintf; class VerifyAuthenticationExceptionTest extends TestCase { - use StringUtilsTrait; - - /** - * @test - * @dataProvider provideExceptionData - */ - public function withErrorCreatesExpectedException(string $code, string $message, ?Throwable $prev): void - { - $e = VerifyAuthenticationException::withError($code, $message, $prev); - - $this->assertEquals(0, $e->getCode()); - $this->assertEquals( - sprintf('Authentication verification failed with the public message "%s"', $message), - $e->getMessage() - ); - $this->assertEquals($code, $e->getErrorCode()); - $this->assertEquals($message, $e->getPublicMessage()); - $this->assertEquals($prev, $e->getPrevious()); - } - - public function provideExceptionData(): iterable - { - return array_map(function () { - return [ - $this->generateRandomString(), - $this->generateRandomString(50), - random_int(0, 1) === 1 ? new Exception('Prev') : null, - ]; - }, range(1, 10)); - } - - /** - * @test - * @dataProvider provideConstructorData - */ - public function constructCreatesExpectedException( - string $errorCode, - string $publicMessage, - string $message, - int $code, - ?Throwable $prev - ): void { - $e = new VerifyAuthenticationException($errorCode, $publicMessage, $message, $code, $prev); - - $this->assertEquals($code, $e->getCode()); - $this->assertEquals($message, $e->getMessage()); - $this->assertEquals($errorCode, $e->getErrorCode()); - $this->assertEquals($publicMessage, $e->getPublicMessage()); - $this->assertEquals($prev, $e->getPrevious()); - } - - public function provideConstructorData(): iterable - { - return array_map(function (int $i) { - return [ - $this->generateRandomString(), - $this->generateRandomString(30), - $this->generateRandomString(50), - $i, - random_int(0, 1) === 1 ? new Exception('Prev') : null, - ]; - }, range(10, 20)); - } - /** @test */ - public function defaultConstructorValuesAreKept(): void + public function createsExpectedExceptionForInvalidApiKey(): void { - $e = new VerifyAuthenticationException('foo', 'bar'); + $e = VerifyAuthenticationException::forInvalidApiKey(); - $this->assertEquals(0, $e->getCode()); - $this->assertEquals('', $e->getMessage()); - $this->assertEquals('foo', $e->getErrorCode()); - $this->assertEquals('bar', $e->getPublicMessage()); - $this->assertNull($e->getPrevious()); + $this->assertEquals('Provided API key does not exist or is invalid.', $e->getMessage()); } } diff --git a/module/Rest/test/Middleware/AuthenticationMiddlewareTest.php b/module/Rest/test/Middleware/AuthenticationMiddlewareTest.php index e373fbea..36dfaeee 100644 --- a/module/Rest/test/Middleware/AuthenticationMiddlewareTest.php +++ b/module/Rest/test/Middleware/AuthenticationMiddlewareTest.php @@ -4,12 +4,10 @@ declare(strict_types=1); namespace ShlinkioTest\Shlink\Rest\Middleware; -use Exception; use Fig\Http\Message\RequestMethodInterface; use PHPUnit\Framework\TestCase; use Prophecy\Argument; use Prophecy\Prophecy\ObjectProphecy; -use Psr\Container\ContainerExceptionInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; @@ -17,20 +15,13 @@ use Psr\Http\Server\RequestHandlerInterface; use Psr\Log\LoggerInterface; use Shlinkio\Shlink\Rest\Action\AuthenticateAction; use Shlinkio\Shlink\Rest\Authentication\Plugin\AuthenticationPluginInterface; -use Shlinkio\Shlink\Rest\Authentication\RequestToHttpAuthPlugin; use Shlinkio\Shlink\Rest\Authentication\RequestToHttpAuthPluginInterface; -use Shlinkio\Shlink\Rest\Exception\NoAuthenticationException; -use Shlinkio\Shlink\Rest\Exception\VerifyAuthenticationException; use Shlinkio\Shlink\Rest\Middleware\AuthenticationMiddleware; -use Shlinkio\Shlink\Rest\Util\RestUtils; -use Throwable; use Zend\Diactoros\Response; use Zend\Diactoros\ServerRequest; use Zend\Expressive\Router\Route; use Zend\Expressive\Router\RouteResult; -use function implode; -use function sprintf; use function Zend\Stratigility\middleware; class AuthenticationMiddlewareTest extends TestCase @@ -93,72 +84,6 @@ class AuthenticationMiddlewareTest extends TestCase )->withMethod(RequestMethodInterface::METHOD_OPTIONS)]; } - /** - * @test - * @dataProvider provideExceptions - */ - public function errorIsReturnedWhenNoValidAuthIsProvided(Throwable $e): void - { - $request = (new ServerRequest())->withAttribute( - RouteResult::class, - RouteResult::fromRoute(new Route('bar', $this->getDummyMiddleware()), []) - ); - $fromRequest = $this->requestToPlugin->fromRequest(Argument::any())->willThrow($e); - $logWarning = $this->logger->warning('Invalid or no authentication provided. {e}', ['e' => $e])->will( - function () { - } - ); - - /** @var Response\JsonResponse $response */ - $response = $this->middleware->process($request, $this->prophesize(RequestHandlerInterface::class)->reveal()); - $payload = $response->getPayload(); - - $this->assertEquals(RestUtils::INVALID_AUTHORIZATION_ERROR, $payload['error']); - $this->assertEquals(sprintf( - 'Expected one of the following authentication headers, but none were provided, ["%s"]', - implode('", "', RequestToHttpAuthPlugin::SUPPORTED_AUTH_HEADERS) - ), $payload['message']); - $fromRequest->shouldHaveBeenCalledOnce(); - $logWarning->shouldHaveBeenCalledOnce(); - } - - public function provideExceptions(): iterable - { - $containerException = new class extends Exception implements ContainerExceptionInterface { - }; - - yield 'container exception' => [$containerException]; - yield 'authentication exception' => [NoAuthenticationException::fromExpectedTypes([])]; - } - - /** @test */ - public function errorIsReturnedWhenVerificationFails(): void - { - $request = (new ServerRequest())->withAttribute( - RouteResult::class, - RouteResult::fromRoute(new Route('bar', $this->getDummyMiddleware()), []) - ); - $e = VerifyAuthenticationException::withError('the_error', 'the_message'); - $plugin = $this->prophesize(AuthenticationPluginInterface::class); - - $verify = $plugin->verify($request)->willThrow($e); - $fromRequest = $this->requestToPlugin->fromRequest(Argument::any())->willReturn($plugin->reveal()); - $logWarning = $this->logger->warning('Authentication verification failed. {e}', ['e' => $e])->will( - function () { - } - ); - - /** @var Response\JsonResponse $response */ - $response = $this->middleware->process($request, $this->prophesize(RequestHandlerInterface::class)->reveal()); - $payload = $response->getPayload(); - - $this->assertEquals('the_error', $payload['error']); - $this->assertEquals('the_message', $payload['message']); - $verify->shouldHaveBeenCalledOnce(); - $fromRequest->shouldHaveBeenCalledOnce(); - $logWarning->shouldHaveBeenCalledOnce(); - } - /** @test */ public function updatedResponseIsReturnedWhenVerificationPasses(): void { diff --git a/module/Rest/test/Middleware/BackwardsCompatibleProblemDetailsMiddlewareTest.php b/module/Rest/test/Middleware/BackwardsCompatibleProblemDetailsMiddlewareTest.php new file mode 100644 index 00000000..4d47c4cb --- /dev/null +++ b/module/Rest/test/Middleware/BackwardsCompatibleProblemDetailsMiddlewareTest.php @@ -0,0 +1,122 @@ +handler = $this->prophesize(RequestHandlerInterface::class); + $this->middleware = new BackwardsCompatibleProblemDetailsMiddleware([ + 404 => 'NOT_FOUND', + 500 => 'INTERNAL_SERVER_ERROR', + ], 0); + } + + /** + * @test + * @dataProvider provideNonProcessableResponses + */ + public function nonProblemDetailsOrInvalidResponsesAreReturnedAsTheyAre(Response $response): void + { + $request = ServerRequestFactory::fromGlobals(); + $response = new Response(); + $handle = $this->handler->handle($request)->willReturn($response); + + $result = $this->middleware->process($request, $this->handler->reveal()); + + $this->assertSame($response, $result); + $handle->shouldHaveBeenCalledOnce(); + } + + public function provideNonProcessableResponses(): iterable + { + yield 'no problem details' => [new Response()]; + yield 'invalid JSON' => [(new Response('data://text/plain,{invalid-json'))->withHeader( + 'Content-Type', + 'application/problem+json' + )]; + } + + /** + * @test + * @dataProvider provideStatusAndTypes + */ + public function properlyMapsTypesBasedOnResponseStatus(Response\JsonResponse $response, string $expectedType): void + { + $request = ServerRequestFactory::fromGlobals()->withUri(new Uri('/v2/something')); + $handle = $this->handler->handle($request)->willReturn($response); + + /** @var Response\JsonResponse $result */ + $result = $this->middleware->process($request, $this->handler->reveal()); + $payload = $result->getPayload(); + + $this->assertEquals($expectedType, $payload['type']); + $this->assertArrayNotHasKey('error', $payload); + $this->assertArrayNotHasKey('message', $payload); + $handle->shouldHaveBeenCalledOnce(); + } + + public function provideStatusAndTypes(): iterable + { + yield [$this->jsonResponse(['type' => 'https://httpstatus.es/404'], 404), 'NOT_FOUND']; + yield [$this->jsonResponse(['type' => 'https://httpstatus.es/500'], 500), 'INTERNAL_SERVER_ERROR']; + yield [$this->jsonResponse(['type' => 'https://httpstatus.es/504'], 504), 'https://httpstatus.es/504']; + yield [$this->jsonResponse(['type' => 'something_else'], 404), 'something_else']; + yield [$this->jsonResponse(['type' => 'something_else'], 500), 'something_else']; + yield [$this->jsonResponse(['type' => 'something_else'], 504), 'something_else']; + } + + /** + * @test + * @dataProvider provideRequestPath + */ + public function mapsDeprecatedPropertiesWhenRequestIsPerformedToVersionOne(string $requestPath): void + { + $request = ServerRequestFactory::fromGlobals()->withUri(new Uri($requestPath)); + $response = $this->jsonResponse([ + 'type' => 'the_type', + 'detail' => 'the_detail', + ]); + $handle = $this->handler->handle($request)->willReturn($response); + + /** @var Response\JsonResponse $result */ + $result = $this->middleware->process($request, $this->handler->reveal()); + $payload = $result->getPayload(); + + $this->assertEquals([ + 'type' => 'the_type', + 'detail' => 'the_detail', + 'error' => 'the_type', + 'message' => 'the_detail', + ], $payload); + $handle->shouldHaveBeenCalledOnce(); + } + + public function provideRequestPath(): iterable + { + yield 'no version' => ['/foo']; + yield 'version one' => ['/v1/foo']; + } + + private function jsonResponse(array $payload, int $status = 200): Response\JsonResponse + { + $headers = ['Content-Type' => 'application/problem+json']; + return new Response\JsonResponse($payload, $status, $headers); + } +} diff --git a/module/Rest/test/Middleware/BodyParserMiddlewareTest.php b/module/Rest/test/Middleware/BodyParserMiddlewareTest.php index fb69c695..829b4b59 100644 --- a/module/Rest/test/Middleware/BodyParserMiddlewareTest.php +++ b/module/Rest/test/Middleware/BodyParserMiddlewareTest.php @@ -6,6 +6,7 @@ namespace ShlinkioTest\Shlink\Rest\Middleware; use PHPUnit\Framework\TestCase; use Prophecy\Argument; +use Prophecy\Prophecy\ProphecyInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; use Shlinkio\Shlink\Rest\Middleware\BodyParserMiddleware; @@ -31,7 +32,10 @@ class BodyParserMiddlewareTest extends TestCase */ public function requestsFromOtherMethodsJustFallbackToNextMiddleware(string $method): void { - $request = (new ServerRequest())->withMethod($method); + $request = $this->prophesize(ServerRequestInterface::class); + $request->getMethod()->willReturn($method); + $request->getParsedBody()->willReturn([]); + $this->assertHandlingRequestJustFallsBackToNext($request); } @@ -45,18 +49,25 @@ class BodyParserMiddlewareTest extends TestCase /** @test */ public function requestsWithNonEmptyBodyJustFallbackToNextMiddleware(): void { - $request = (new ServerRequest())->withParsedBody(['foo' => 'bar'])->withMethod('POST'); + $request = $this->prophesize(ServerRequestInterface::class); + $request->getMethod()->willReturn('POST'); + $request->getParsedBody()->willReturn(['foo' => 'bar']); + $this->assertHandlingRequestJustFallsBackToNext($request); } - private function assertHandlingRequestJustFallsBackToNext(ServerRequestInterface $request): void + private function assertHandlingRequestJustFallsBackToNext(ProphecyInterface $requestMock): void { + $getContentType = $requestMock->getHeaderLine('Content-type')->willReturn(''); + $request = $requestMock->reveal(); + $nextHandler = $this->prophesize(RequestHandlerInterface::class); $handle = $nextHandler->handle($request)->willReturn(new Response()); $this->middleware->process($request, $nextHandler->reveal()); $handle->shouldHaveBeenCalledOnce(); + $getContentType->shouldNotHaveBeenCalled(); } /** @test */ diff --git a/module/Rest/test/Middleware/CrossDomainMiddlewareTest.php b/module/Rest/test/Middleware/CrossDomainMiddlewareTest.php index ebc88080..1716c19e 100644 --- a/module/Rest/test/Middleware/CrossDomainMiddlewareTest.php +++ b/module/Rest/test/Middleware/CrossDomainMiddlewareTest.php @@ -8,12 +8,14 @@ use PHPUnit\Framework\TestCase; use Prophecy\Argument; use Prophecy\Prophecy\ObjectProphecy; use Psr\Http\Server\RequestHandlerInterface; +use Shlinkio\Shlink\Rest\Authentication; use Shlinkio\Shlink\Rest\Middleware\CrossDomainMiddleware; use Zend\Diactoros\Response; use Zend\Diactoros\ServerRequest; use Zend\Expressive\Router\Route; use Zend\Expressive\Router\RouteResult; +use function implode; use function Zend\Stratigility\middleware; class CrossDomainMiddlewareTest extends TestCase @@ -39,6 +41,7 @@ class CrossDomainMiddlewareTest extends TestCase $this->assertSame($originalResponse, $response); $headers = $response->getHeaders(); + $this->assertArrayNotHasKey('Access-Control-Allow-Origin', $headers); $this->assertArrayNotHasKey('Access-Control-Expose-Headers', $headers); $this->assertArrayNotHasKey('Access-Control-Allow-Methods', $headers); @@ -59,8 +62,12 @@ class CrossDomainMiddlewareTest extends TestCase $this->assertNotSame($originalResponse, $response); $headers = $response->getHeaders(); - $this->assertArrayHasKey('Access-Control-Allow-Origin', $headers); - $this->assertArrayHasKey('Access-Control-Expose-Headers', $headers); + + $this->assertEquals('local', $response->getHeaderLine('Access-Control-Allow-Origin')); + $this->assertEquals(implode(', ', [ + Authentication\Plugin\ApiKeyHeaderPlugin::HEADER_NAME, + Authentication\Plugin\AuthorizationHeaderPlugin::HEADER_NAME, + ]), $response->getHeaderLine('Access-Control-Expose-Headers')); $this->assertArrayNotHasKey('Access-Control-Allow-Methods', $headers); $this->assertArrayNotHasKey('Access-Control-Max-Age', $headers); $this->assertArrayNotHasKey('Access-Control-Allow-Headers', $headers); @@ -70,18 +77,25 @@ class CrossDomainMiddlewareTest extends TestCase public function optionsRequestIncludesMoreHeaders(): void { $originalResponse = new Response(); - $request = (new ServerRequest())->withMethod('OPTIONS')->withHeader('Origin', 'local'); + $request = (new ServerRequest()) + ->withMethod('OPTIONS') + ->withHeader('Origin', 'local') + ->withHeader('Access-Control-Request-Headers', 'foo, bar, baz'); $this->handler->handle(Argument::any())->willReturn($originalResponse)->shouldBeCalledOnce(); $response = $this->middleware->process($request, $this->handler->reveal()); $this->assertNotSame($originalResponse, $response); $headers = $response->getHeaders(); - $this->assertArrayHasKey('Access-Control-Allow-Origin', $headers); - $this->assertArrayHasKey('Access-Control-Expose-Headers', $headers); + + $this->assertEquals('local', $response->getHeaderLine('Access-Control-Allow-Origin')); + $this->assertEquals(implode(', ', [ + Authentication\Plugin\ApiKeyHeaderPlugin::HEADER_NAME, + Authentication\Plugin\AuthorizationHeaderPlugin::HEADER_NAME, + ]), $response->getHeaderLine('Access-Control-Expose-Headers')); $this->assertArrayHasKey('Access-Control-Allow-Methods', $headers); - $this->assertArrayHasKey('Access-Control-Max-Age', $headers); - $this->assertArrayHasKey('Access-Control-Allow-Headers', $headers); + $this->assertEquals('1000', $response->getHeaderLine('Access-Control-Max-Age')); + $this->assertEquals('foo, bar, baz', $response->getHeaderLine('Access-Control-Allow-Headers')); } /** diff --git a/module/Rest/test/Service/ApiKeyServiceTest.php b/module/Rest/test/Service/ApiKeyServiceTest.php index d79cea41..caa50bf1 100644 --- a/module/Rest/test/Service/ApiKeyServiceTest.php +++ b/module/Rest/test/Service/ApiKeyServiceTest.php @@ -27,65 +27,49 @@ class ApiKeyServiceTest extends TestCase $this->service = new ApiKeyService($this->em->reveal()); } - /** @test */ - public function keyIsProperlyCreated() + /** + * @test + * @dataProvider provideCreationDate + */ + public function apiKeyIsProperlyCreated(?Chronos $date): void { $this->em->flush()->shouldBeCalledOnce(); $this->em->persist(Argument::type(ApiKey::class))->shouldBeCalledOnce(); - $key = $this->service->create(); - $this->assertNull($key->getExpirationDate()); - } - - /** @test */ - public function keyIsProperlyCreatedWithExpirationDate() - { - $this->em->flush()->shouldBeCalledOnce(); - $this->em->persist(Argument::type(ApiKey::class))->shouldBeCalledOnce(); - - $date = Chronos::parse('2030-01-01'); $key = $this->service->create($date); - $this->assertSame($date, $key->getExpirationDate()); + + $this->assertEquals($date, $key->getExpirationDate()); } - /** @test */ - public function checkReturnsFalseWhenKeyIsInvalid() + public function provideCreationDate(): iterable + { + yield 'no expiration date' => [null]; + yield 'expiration date' => [Chronos::parse('2030-01-01')]; + } + + /** + * @test + * @dataProvider provideInvalidApiKeys + */ + public function checkReturnsFalseForInvalidApiKeys(?ApiKey $invalidKey): void { $repo = $this->prophesize(EntityRepository::class); - $repo->findOneBy(['key' => '12345'])->willReturn(null) + $repo->findOneBy(['key' => '12345'])->willReturn($invalidKey) ->shouldBeCalledOnce(); $this->em->getRepository(ApiKey::class)->willReturn($repo->reveal()); $this->assertFalse($this->service->check('12345')); } - /** @test */ - public function checkReturnsFalseWhenKeyIsDisabled() + public function provideInvalidApiKeys(): iterable { - $key = new ApiKey(); - $key->disable(); - $repo = $this->prophesize(EntityRepository::class); - $repo->findOneBy(['key' => '12345'])->willReturn($key) - ->shouldBeCalledOnce(); - $this->em->getRepository(ApiKey::class)->willReturn($repo->reveal()); - - $this->assertFalse($this->service->check('12345')); + yield 'non-existent api key' => [null]; + yield 'disabled api key' => [(new ApiKey())->disable()]; + yield 'expired api key' => [new ApiKey(Chronos::now()->subDay())]; } /** @test */ - public function checkReturnsFalseWhenKeyIsExpired() - { - $key = new ApiKey(Chronos::now()->subDay()); - $repo = $this->prophesize(EntityRepository::class); - $repo->findOneBy(['key' => '12345'])->willReturn($key) - ->shouldBeCalledOnce(); - $this->em->getRepository(ApiKey::class)->willReturn($repo->reveal()); - - $this->assertFalse($this->service->check('12345')); - } - - /** @test */ - public function checkReturnsTrueWhenConditionsAreFavorable() + public function checkReturnsTrueWhenConditionsAreFavorable(): void { $repo = $this->prophesize(EntityRepository::class); $repo->findOneBy(['key' => '12345'])->willReturn(new ApiKey()) @@ -96,7 +80,7 @@ class ApiKeyServiceTest extends TestCase } /** @test */ - public function disableThrowsExceptionWhenNoTokenIsFound() + public function disableThrowsExceptionWhenNoApiKeyIsFound(): void { $repo = $this->prophesize(EntityRepository::class); $repo->findOneBy(['key' => '12345'])->willReturn(null) @@ -104,11 +88,12 @@ class ApiKeyServiceTest extends TestCase $this->em->getRepository(ApiKey::class)->willReturn($repo->reveal()); $this->expectException(InvalidArgumentException::class); + $this->service->disable('12345'); } /** @test */ - public function disableReturnsDisabledKeyWhenFOund() + public function disableReturnsDisabledApiKeyWhenFound(): void { $key = new ApiKey(); $repo = $this->prophesize(EntityRepository::class); @@ -125,24 +110,32 @@ class ApiKeyServiceTest extends TestCase } /** @test */ - public function listFindsAllApiKeys() + public function listFindsAllApiKeys(): void { + $expectedApiKeys = [new ApiKey(), new ApiKey(), new ApiKey()]; + $repo = $this->prophesize(EntityRepository::class); - $repo->findBy([])->willReturn([]) + $repo->findBy([])->willReturn($expectedApiKeys) ->shouldBeCalledOnce(); $this->em->getRepository(ApiKey::class)->willReturn($repo->reveal()); - $this->service->listKeys(); + $result = $this->service->listKeys(); + + $this->assertEquals($expectedApiKeys, $result); } /** @test */ - public function listEnabledFindsOnlyEnabledApiKeys() + public function listEnabledFindsOnlyEnabledApiKeys(): void { + $expectedApiKeys = [new ApiKey(), new ApiKey(), new ApiKey()]; + $repo = $this->prophesize(EntityRepository::class); - $repo->findBy(['enabled' => true])->willReturn([]) + $repo->findBy(['enabled' => true])->willReturn($expectedApiKeys) ->shouldBeCalledOnce(); $this->em->getRepository(ApiKey::class)->willReturn($repo->reveal()); - $this->service->listKeys(true); + $result = $this->service->listKeys(true); + + $this->assertEquals($expectedApiKeys, $result); } } diff --git a/module/Rest/test/Util/RestUtilsTest.php b/module/Rest/test/Util/RestUtilsTest.php deleted file mode 100644 index c958594b..00000000 --- a/module/Rest/test/Util/RestUtilsTest.php +++ /dev/null @@ -1,41 +0,0 @@ -assertEquals( - RestUtils::INVALID_SHORTCODE_ERROR, - RestUtils::getRestErrorCodeFromException(new InvalidShortCodeException()) - ); - $this->assertEquals( - RestUtils::INVALID_URL_ERROR, - RestUtils::getRestErrorCodeFromException(new InvalidUrlException()) - ); - $this->assertEquals( - RestUtils::INVALID_ARGUMENT_ERROR, - RestUtils::getRestErrorCodeFromException(new InvalidArgumentException()) - ); - $this->assertEquals( - RestUtils::INVALID_CREDENTIALS_ERROR, - RestUtils::getRestErrorCodeFromException(new AuthenticationException()) - ); - $this->assertEquals( - RestUtils::UNKNOWN_ERROR, - RestUtils::getRestErrorCodeFromException(new WrongIpException()) - ); - } -} diff --git a/phpstan.neon b/phpstan.neon index 8b5db673..2d9d960d 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,7 +1,5 @@ parameters: ignoreErrors: - - '#is not subtype of Throwable#' - - '#ObjectManager::flush()#' - '#Undefined variable: \$metadata#' - '#AbstractQuery::setParameters()#' - '#mustRun()#' diff --git a/phpunit-api.xml b/phpunit-api.xml index 69132097..6e481fe5 100644 --- a/phpunit-api.xml +++ b/phpunit-api.xml @@ -1,7 +1,7 @@ diff --git a/phpunit-db.xml b/phpunit-db.xml index eab4be28..86cdbbc6 100644 --- a/phpunit-db.xml +++ b/phpunit-db.xml @@ -1,7 +1,7 @@ diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 1ae25124..67d08507 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,7 +1,7 @@ diff --git a/public/index.php b/public/index.php index 336f5cc2..78bb412a 100644 --- a/public/index.php +++ b/public/index.php @@ -2,11 +2,5 @@ declare(strict_types=1); -use Psr\Container\ContainerInterface; -use Zend\Expressive\Application; - -(function () { - /** @var ContainerInterface $container */ - $container = include __DIR__ . '/../config/container.php'; - $container->get(Application::class)->run(); -})(); +$run = require __DIR__ . '/../config/run.php'; +$run();