diff --git a/.dockerignore b/.dockerignore
index 9a48c84c..f9102acb 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -17,7 +17,8 @@ indocker
docker-*
phpstan.neon
php*xml*
-infection.json
+infection*
**/test*
build*
**/.*
+bin/helper
diff --git a/.gitattributes b/.gitattributes
index 53b0a935..4d66fe58 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -10,7 +10,6 @@
.gitattributes export-ignore
.gitignore export-ignore
.phpstorm.meta.php export-ignore
-.scrutinizer.yml export-ignore
.travis.yml export-ignore
build.sh export-ignore
CHANGELOG.md export-ignore
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 00000000..c426f4a3
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,319 @@
+name: Continuous integration
+
+on:
+ pull_request: null
+ push:
+ branches:
+ - main
+ - develop
+
+jobs:
+ lint:
+ runs-on: ubuntu-20.04
+ strategy:
+ matrix:
+ php-version: ['7.4']
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v2
+ - name: Use PHP
+ uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php-version }}
+ tools: composer
+ extensions: swoole-4.5.9
+ coverage: none
+ - run: composer install --no-interaction --prefer-dist
+ - run: composer cs
+
+ static-analysis:
+ runs-on: ubuntu-20.04
+ strategy:
+ matrix:
+ php-version: ['7.4']
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v2
+ - name: Use PHP
+ uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php-version }}
+ tools: composer
+ extensions: swoole-4.5.9
+ coverage: none
+ - run: composer install --no-interaction --prefer-dist
+ - run: composer stan
+
+ unit-tests:
+ runs-on: ubuntu-20.04
+ continue-on-error: ${{ matrix.php-version == '8.0' }}
+ strategy:
+ matrix:
+ php-version: ['7.4', '8.0']
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v2
+ - name: Use PHP
+ uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php-version }}
+ tools: composer
+ extensions: swoole-4.5.9
+ coverage: pcov
+ ini-values: pcov.directory=module
+ - if: ${{ matrix.php-version == '8.0' }}
+ run: composer install --no-interaction --prefer-dist --ignore-platform-req=php
+ - if: ${{ matrix.php-version != '8.0' }}
+ run: composer install --no-interaction --prefer-dist
+ - run: composer test:unit:ci
+ - uses: actions/upload-artifact@v2
+ if: ${{ matrix.php-version == '7.4' }}
+ with:
+ name: coverage-unit
+ path: |
+ build/coverage-unit
+ build/coverage-unit.cov
+
+ db-tests-sqlite:
+ runs-on: ubuntu-20.04
+ strategy:
+ matrix:
+ php-version: ['7.4', '8.0']
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v2
+ - name: Use PHP
+ uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php-version }}
+ tools: composer
+ extensions: swoole-4.5.9
+ coverage: pcov
+ ini-values: pcov.directory=module
+ - if: ${{ matrix.php-version == '8.0' }}
+ run: composer install --no-interaction --prefer-dist --ignore-platform-req=php
+ - if: ${{ matrix.php-version != '8.0' }}
+ run: composer install --no-interaction --prefer-dist
+ - run: composer test:db:sqlite:ci
+ - uses: actions/upload-artifact@v2
+ if: ${{ matrix.php-version == '7.4' }}
+ with:
+ name: coverage-db
+ path: |
+ build/coverage-db
+ build/coverage-db.cov
+
+ db-tests-mysql:
+ runs-on: ubuntu-20.04
+ strategy:
+ matrix:
+ php-version: ['7.4', '8.0']
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v2
+ - name: Start database server
+ run: docker-compose -f docker-compose.yml -f docker-compose.ci.yml up -d shlink_db
+ - name: Use PHP
+ uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php-version }}
+ tools: composer
+ extensions: swoole-4.5.9
+ coverage: none
+ - if: ${{ matrix.php-version == '8.0' }}
+ run: composer install --no-interaction --prefer-dist --ignore-platform-req=php
+ - if: ${{ matrix.php-version != '8.0' }}
+ run: composer install --no-interaction --prefer-dist
+ - run: composer test:db:mysql
+
+ db-tests-maria:
+ runs-on: ubuntu-20.04
+ strategy:
+ matrix:
+ php-version: ['7.4', '8.0']
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v2
+ - name: Start database server
+ run: docker-compose -f docker-compose.yml -f docker-compose.ci.yml up -d shlink_db_maria
+ - name: Use PHP
+ uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php-version }}
+ tools: composer
+ extensions: swoole-4.5.9
+ coverage: none
+ - if: ${{ matrix.php-version == '8.0' }}
+ run: composer install --no-interaction --prefer-dist --ignore-platform-req=php
+ - if: ${{ matrix.php-version != '8.0' }}
+ run: composer install --no-interaction --prefer-dist
+ - run: composer test:db:maria
+
+ db-tests-postgres:
+ runs-on: ubuntu-20.04
+ strategy:
+ matrix:
+ php-version: ['7.4', '8.0']
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v2
+ - name: Start database server
+ run: docker-compose -f docker-compose.yml -f docker-compose.ci.yml up -d shlink_db_postgres
+ - name: Use PHP
+ uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php-version }}
+ tools: composer
+ extensions: swoole-4.5.9
+ coverage: none
+ - if: ${{ matrix.php-version == '8.0' }}
+ run: composer install --no-interaction --prefer-dist --ignore-platform-req=php
+ - if: ${{ matrix.php-version != '8.0' }}
+ run: composer install --no-interaction --prefer-dist
+ - run: composer test:db:postgres
+
+ db-tests-ms:
+ runs-on: ubuntu-20.04
+ strategy:
+ matrix:
+ php-version: ['7.4', '8.0']
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v2
+ - name: Install MSSQL ODBC
+ run: sudo ./data/infra/ci/install-ms-odbc.sh
+ - name: Start database server
+ run: docker-compose -f docker-compose.yml -f docker-compose.ci.yml up -d shlink_db_ms
+ - name: Use PHP
+ uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php-version }}
+ tools: composer
+ extensions: swoole-4.5.9, pdo_sqlsrv-5.9.0beta2
+ coverage: none
+ - if: ${{ matrix.php-version == '8.0' }}
+ run: composer install --no-interaction --prefer-dist --ignore-platform-req=php
+ - if: ${{ matrix.php-version != '8.0' }}
+ run: composer install --no-interaction --prefer-dist
+ - name: Create test database
+ run: docker-compose exec -T shlink_db_ms /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P 'Passw0rd!' -Q "CREATE DATABASE shlink_test;"
+ - run: composer test:db:ms
+
+ api-tests:
+ runs-on: ubuntu-20.04
+ continue-on-error: ${{ matrix.php-version == '8.0' }}
+ strategy:
+ matrix:
+ php-version: ['7.4', '8.0']
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v2
+ - name: Start database server
+ run: docker-compose -f docker-compose.yml -f docker-compose.ci.yml up -d shlink_db
+ - name: Use PHP
+ uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php-version }}
+ tools: composer
+ extensions: swoole-4.5.9
+ coverage: pcov
+ ini-values: pcov.directory=module
+ - if: ${{ matrix.php-version == '8.0' }}
+ run: composer install --no-interaction --prefer-dist --ignore-platform-req=php
+ - if: ${{ matrix.php-version != '8.0' }}
+ run: composer install --no-interaction --prefer-dist
+ - run: bin/test/run-api-tests.sh
+ - uses: actions/upload-artifact@v2
+ if: ${{ matrix.php-version == '7.4' }}
+ with:
+ name: coverage-api
+ path: |
+ build/coverage-api
+ build/coverage-api.cov
+
+ mutation-tests:
+ needs:
+ - unit-tests
+ - db-tests-sqlite
+ - api-tests
+ runs-on: ubuntu-20.04
+ strategy:
+ matrix:
+ php-version: ['7.4', '8.0']
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v2
+ - name: Use PHP
+ uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php-version }}
+ tools: composer
+ extensions: swoole-4.5.9
+ coverage: pcov
+ ini-values: pcov.directory=module
+ - if: ${{ matrix.php-version == '8.0' }}
+ run: composer install --no-interaction --prefer-dist --ignore-platform-req=php
+ - if: ${{ matrix.php-version != '8.0' }}
+ run: composer install --no-interaction --prefer-dist
+ - uses: actions/download-artifact@v2
+ with:
+ path: build
+ - run: composer infect:ci
+
+ upload-coverage:
+ needs:
+ - unit-tests
+ - db-tests-sqlite
+ - api-tests
+ runs-on: ubuntu-20.04
+ strategy:
+ matrix:
+ php-version: ['7.4']
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v2
+ - name: Use PHP
+ uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php-version }}
+ coverage: pcov
+ ini-values: pcov.directory=module
+ - uses: actions/download-artifact@v2
+ with:
+ path: build
+ - run: mv build/coverage-unit/coverage-unit.cov build/coverage-unit.cov
+ - run: mv build/coverage-db/coverage-db.cov build/coverage-db.cov
+ - run: mv build/coverage-api/coverage-api.cov build/coverage-api.cov
+ - run: wget https://phar.phpunit.de/phpcov-8.2.0.phar
+ - run: php phpcov-8.2.0.phar merge build --clover build/clover.xml
+ - name: Publish coverage
+ uses: codecov/codecov-action@v1
+ with:
+ file: ./build/clover.xml
+
+ delete-artifacts:
+ needs:
+ - mutation-tests
+ - upload-coverage
+ runs-on: ubuntu-20.04
+ steps:
+ - uses: geekyeggo/delete-artifact@v1
+ with:
+ name: |
+ coverage-unit
+ coverage-db
+ coverage-api
+
+ build-docker-image:
+ runs-on: ubuntu-20.04
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v2
+ - uses: marceloprado/has-changed-path@v1
+ id: changed-dockerfile
+ with:
+ paths: ./Dockerfile
+ - if: ${{ steps.changed-dockerfile.outputs.changed == 'true' }}
+ run: docker build -t shlink-docker-image:temp .
+ - if: ${{ steps.changed-dockerfile.outputs.changed != 'true' }}
+ run: echo "Dockerfile didn't change. Skipped"
diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml
index 78f981ab..c1009f1c 100644
--- a/.github/workflows/publish-release.yml
+++ b/.github/workflows/publish-release.yml
@@ -16,7 +16,7 @@ jobs:
with:
php-version: '7.4' # Publish release with lowest supported PHP version
tools: composer
- extensions: swoole-4.5.5
+ extensions: swoole-4.5.9
- name: Generate release assets
run: ./build.sh ${GITHUB_REF#refs/tags/v}
- name: Publish release with assets
diff --git a/.scrutinizer.yml b/.scrutinizer.yml
deleted file mode 100644
index ed831706..00000000
--- a/.scrutinizer.yml
+++ /dev/null
@@ -1,16 +0,0 @@
-tools:
- external_code_coverage:
- timeout: 600
-checks:
- php:
- code_rating: true
- duplication: true
-build:
- dependencies:
- override:
- - composer install --no-interaction --no-scripts --ignore-platform-reqs
- nodes:
- analysis:
- tests:
- override:
- - php-scrutinizer-run
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index 3bf55b55..00000000
--- a/.travis.yml
+++ /dev/null
@@ -1,56 +0,0 @@
-dist: bionic
-
-language: php
-
-branches:
- only:
- - /.*/
-
-services:
- - docker
-
-cache:
- directories:
- - $HOME/.composer/cache/files
-
-jobs:
- fast_finish: true
- allow_failures:
- - php: 'nightly'
- include:
- - name: "CI - 8.0"
- php: 'nightly'
- env:
- - COMPOSER_FLAGS='--ignore-platform-reqs'
- - name: "CI - 7.4"
- php: '7.4'
- env:
- - COMPOSER_FLAGS=''
-
-before_install:
- - echo 'extension = apcu.so' >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini
- - phpenv config-rm xdebug.ini || return 0
- - sudo ./data/infra/ci/install-ms-odbc.sh
- - docker-compose -f docker-compose.yml -f docker-compose.ci.yml up -d shlink_db_ms shlink_db shlink_db_postgres shlink_db_maria
- - yes | pecl install pdo_sqlsrv-5.9.0preview1 swoole-4.5.5 pcov
-
-install:
- - composer self-update
- - composer install --no-interaction --prefer-dist $COMPOSER_FLAGS
-
-before_script:
- - docker-compose exec shlink_db_ms /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P 'Passw0rd!' -Q "CREATE DATABASE shlink_test;"
- - mkdir build
- - export DOCKERFILE_CHANGED=$(git diff ${TRAVIS_COMMIT_RANGE:-origin/main} --name-only | grep Dockerfile)
-
-script:
- - composer ci
- - bin/test/run-api-tests.sh
- - if [[ ! -z "${DOCKERFILE_CHANGED}" && "${TRAVIS_PHP_VERSION}" == "7.4" ]]; then docker build -t shlink-docker-image:temp . ; fi
-
-after_success:
- - rm -f build/clover.xml
- - wget https://phar.phpunit.de/phpcov-7.0.2.phar
- - php phpcov-7.0.2.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 9ec8f4df..8f034cd0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,40 @@ 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).
+## [2.5.0] - 2021-01-17
+### Added
+* [#795](https://github.com/shlinkio/shlink/issues/795) and [#882](https://github.com/shlinkio/shlink/issues/882) Added new roles system to API keys.
+
+ API keys can have any combinations of these two roles now, allowing to limit their interactions:
+
+ * Can interact only with short URLs created with that API key.
+ * Can interact only with short URLs for a specific domain.
+
+* [#833](https://github.com/shlinkio/shlink/issues/833) Added support to connect through unix socket when using an external MySQL, MariaDB or Postgres database.
+
+ It can be provided during the installation, or as the `DB_UNIX_SOCKET` env var for the docker image.
+
+* [#869](https://github.com/shlinkio/shlink/issues/869) Added support for Mercure Hub 0.10.
+* [#896](https://github.com/shlinkio/shlink/issues/896) Added support for unicode characters in custom slugs.
+* [#930](https://github.com/shlinkio/shlink/issues/930) Added new `bin/set-option` script that allows changing individual configuration options on existing shlink instances.
+* [#877](https://github.com/shlinkio/shlink/issues/877) Improved API tests on CORS, and "refined" middleware handling it.
+
+### Changed
+* [#912](https://github.com/shlinkio/shlink/issues/912) Changed error templates to be plain html files, removing the dependency on `league/plates` package.
+* [#875](https://github.com/shlinkio/shlink/issues/875) Updated to `mezzio/mezzio-swoole` v3.1.
+* [#952](https://github.com/shlinkio/shlink/issues/952) Simplified in-project docs, by keeping only the basics and linking to the websites docs for anything else.
+
+### Deprecated
+* [#917](https://github.com/shlinkio/shlink/issues/917) Deprecated `/{shortCode}/qr-code/{size}` URL, in favor of providing the size in the query instead, `/{shortCode}/qr-code?size={size}`.
+* [#924](https://github.com/shlinkio/shlink/issues/924) Deprecated mechanism to provide config options to the docker image through volumes. Use the env vars instead as a direct replacement.
+
+### Removed
+* *Nothing*
+
+### Fixed
+* *Nothing*
+
+
## [2.4.2] - 2020-11-22
### Added
* *Nothing*
diff --git a/Dockerfile b/Dockerfile
index cc7c403d..9d7e0bef 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -2,7 +2,7 @@ FROM php:7.4.11-alpine3.12 as base
ARG SHLINK_VERSION=2.4.0
ENV SHLINK_VERSION ${SHLINK_VERSION}
-ENV SWOOLE_VERSION 4.5.5
+ENV SWOOLE_VERSION 4.5.9
ENV LC_ALL "C"
WORKDIR /etc/shlink
diff --git a/README.md b/README.md
index 1b03c048..3a7373b2 100644
--- a/README.md
+++ b/README.md
@@ -1,44 +1,39 @@

-[](https://travis-ci.com/shlinkio/shlink)
-[](https://scrutinizer-ci.com/g/shlinkio/shlink/)
-[](https://scrutinizer-ci.com/g/shlinkio/shlink/)
+[](https://github.com/shlinkio/shlink/actions?query=workflow%3A%22Continuous+integration%22)
+[](https://app.codecov.io/gh/shlinkio/shlink)
[](https://packagist.org/packages/shlinkio/shlink)
-[](https://hub.docker.com/r/shlinkio/shlink/)
+[](https://hub.docker.com/r/shlinkio/shlink/)
[](https://github.com/shlinkio/shlink/blob/main/LICENSE)
[](https://slnk.to/donate)
A PHP-based self-hosted URL shortener that can be used to serve shortened URLs under your own custom domain.
-> This document references Shlink 2.x. If you are using an older version and want to upgrade, follow the [UPGRADE](UPGRADE.md) doc.
-
-> If you are trying to find out how to run the project in development mode or how to provide contributions, read the [CONTRIBUTING](CONTRIBUTING.md) doc.
-
## Table of Contents
-- [Installation](#installation)
+- [Full documentation](#full-documentation)
+- [Docker image](#docker-image)
+- [Self hosted](#self-hosted)
- [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)
-- [Multiple domains](#multiple-domains)
- - [Management](#management)
- - [Visits](#visits)
- - [Special redirects](#special-redirects)
+- [Contributing](#contributing)
-## Installation
+## Full documentation
-> 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)
+This document contains the very basics to get started with Shlink. If you want to learn everything you can do with it, visit the [full searchable documentation](https://shlink.io/documentation/).
+
+## Docker image
+
+Starting with version 1.15.0, an official docker image is provided. You can learn how to use it by reading [the docs](https://shlink.io/documentation/install-docker-image/).
+
+The idea is that you can just generate a container using the image and provide the custom config via env vars.
+
+## Self hosted
First, make sure the host where you are going to run shlink fulfills these requirements:
-* PHP 7.4 or greater with JSON, curl, PDO, intl and gd extensions enabled.
+* PHP 7.4 with JSON, curl, PDO, intl and gd extensions enabled (PHP 8.0 support is coming).
* MySQL, MariaDB, PostgreSQL, Microsoft SQL Server or SQLite.
* The web server of your choice with PHP integration (Apache or Nginx recommended).
@@ -64,7 +59,7 @@ In order to run Shlink, you will need a built version of the project. There are
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.com/shlinkio/shlink), attaching the 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 a [GitHub workflow](https://github.com/shlinkio/shlink/actions?query=workflow%3A%22Publish+release%22), attaching the generated dist file to it.
### Configure
@@ -75,162 +70,6 @@ Despite how you built the project, you now need to configure it, by following th
* 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.**
* 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.
-### Serve
-
-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.
-
-* **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.4-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/mezzio-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/mezzio-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
-
-Geo-locating visits to your short links is a time-consuming task. When serving Shlink with swoole, the geo-location task is automatically run asynchronously just after a visit to a short URL happens.
-
-However, if you are not serving Shlink with swoole, you will have to schedule the geo-location task to be run regularly in the background (for example, using cron jobs):
-
-The command you need to run is `/path/to/shlink/bin/cli visit:locate`, and you can optionally provide the `-q` flag to remove any output and avoid your cron logs to be polluted.
-
-## Update to new version
-
-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 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` 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.
-
-**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
-
-Starting with version 1.15.0, an official docker image is provided. You can learn how to use it by reading [the docs](docker/README.md).
-
-The idea is that you can just generate a container using the image and provide custom config via env vars.
-
## Using shlink
Once shlink is installed, there are two main ways to interact with it:
@@ -243,109 +82,13 @@ Once shlink is installed, there are two main ways to interact with it:
* **The REST API**. The complete docs on how to use the API can be found [here](https://shlink.io/documentation/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.
+ 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 hosted by yourself.
Both the API and CLI allow you to do the same operations, except for API key management, which can be done from the command line interface only.
-### Shlink CLI Help
+## Contributing
-```
-Usage:
- command [options] [arguments]
-
-Options:
- -h, --help Display this help message
- -q, --quiet Do not output any message
- -V, --version Display this application version
- --ansi Force ANSI output
- --no-ansi Disable ANSI output
- -n, --no-interaction Do not ask any interactive question
- -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
-
-Available commands:
- help Displays help for a command
- list Lists commands
- api-key
- api-key:disable Disables an API key.
- api-key:generate Generates a new valid API key.
- api-key:list Lists all the available API keys.
- db
- db:create Creates the database needed for shlink to work. It will do nothing if the database already exists
- db:migrate Runs database migrations, which will ensure the shlink database is up to date.
- short-url
- short-url:delete Deletes a short URL
- short-url:generate Generates a short URL for provided long URL and returns it
- short-url:list List all short URLs
- short-url:parse Returns the long URL behind a short code
- short-url:visits Returns the detailed visits information for provided short code
- tag
- tag:create Creates one or more tags.
- tag:delete Deletes one or more tags.
- tag:list Lists existing tags.
- tag:rename Renames one existing tag.
- visit
- visit:locate Resolves visits origin locations.
-```
-
-## Multiple domains
-
-While in many cases you will just have one short domain and you'll want all your short URLs to be served from it, there are some cases in which you might want to have multiple short domains served from the same Shlink instance.
-
-If that's the case, you need to understand how Shlink will behave when managing your short URLs or any of them is visited.
-
-### Management
-
-When you create a short URL it is possible to optionally pass a `domain` param. If you don't pass it, the short URL will be created for the default domain (the one provided during Shlink's installation or in the `SHORT_DOMAIN_HOST` env var when using the docker image).
-
-However, if you pass it, the short URL will be "linked" to that domain.
-
-> Note that, if the default domain is passed, Shlink will ignore it and will behave as if no `domain` param was provided.
-
-The main benefit of being able to pass the domain is that Shlink will allow the same custom slug to be used in multiple short URLs, as long as the domain is different (like `example.com/my-compaign`, `another.com/my-compaign` and `foo.com/my-compaign`).
-
-Then, each short URL will be tracked separately and you will be able to define specific tags and metadata for each one of them.
-
-However, this has a side effect. When you try to interact with an existing short URL (editing tags, editing meta, resolving it or deleting it), either from the REST API or the CLI tool, you will have to provide the domain appropriately.
-
-Let's imagine this situation. Shlink's default domain is `example.com`, and you have the next short URLs:
-
-* `https://example.com/abc123` -> a regular short URL where no domain was provided.
-* `https://example.com/my-campaign` -> a regular short URL where no domain was provided, but it has a custom slug.
-* `https://another.com/my-campaign` -> a short URL where the `another.com` domain was provided, and it has a custom slug.
-* `https://another.com/def456` -> a short URL where the `another.com` domain was provided.
-
-These are some of the results you will get when trying to interact with them, depending on the params you provide:
-
-* Providing just the `abc123` short code -> the first URL will be matched.
-* Providing just the `my-campaign` short code -> the second URL will be matched, since you did not specify a domain, therefor, Shlink looks for the one with the short code/slug `my-campaign` which is also linked to default domain (or not linked to any domain, to be more accurate).
-* Providing the `my-campaign` short code and the `another.com` domain -> The third one will be matched.
-* Providing just the `def456` short code -> Shlink will fail/not find any short URL, since there's none with the short code `def456` linked to default domain.
-* Providing the `def456` short code and the `another.com` domain -> The fourth short URL will be matched.
-* Providing any short code and the `foo.com` domain -> Again, no short URL will be found, as there's none linked to `foo.com` domain.
-
-### Visits
-
-Before adding support for multiple domains, you could point as many domains as you wanted to Shlink, and they would have always worked for existing short codes/slugs.
-
-In order to keep backwards compatibility, Shlink's behavior when a short URL is visited is slightly different, getting to fallback in some cases.
-
-Let's continue with previous example, and also consider we have three domains that will resolve to our Shlink instance, which are `example.com`, `another.com` and `foo.com`.
-
-With that in mind, this is how Shlink will behave when the next short URLs are visited:
-
-* `https://another.com/abc123` -> There was no short URL specifically defined for domain `another.com` and short code `abc123`, but it exists for default domain (`example.com`), so it will fall back to it and redirect to where `example.com/abc123` is configured to redirect.
-* `https://example.com/def456` -> The fall-back does not happen from default domain to specific ones, only the other way around (like in previous case). Because of that, this one will result in a not-found URL, even though the `def456` short code exists for `another.com` domain.
-* `https://foo.com/abc123` -> This will also fall-back to `example.com/abc123`, like in the first case.
-* `https://another.com/non-existing` -> The combination of `another.com` domain with the `non-existing` slug does not exist, so Shlink will try to fall-back to the same but for default domain (`example.com`). However, since that combination does not exist either, it will result in a not-found URL.
-* Any other short URL visited exactly as it was configured will, of course, resolve as expected.
-
-### Special redirects
-
-It is currently possible to configure some special redirects when the base domain is visited, a URL does not match, or an invalid/disabled short URL is visited.
-
-Those are configured during Shlink's installation or via env vars when using the docker image.
-
-Currently those are all shared for all domains serving the same Shlink instance, but the plan is to update that and allow specific ones for every existing domain.
+If you are trying to find out how to run the project in development mode or how to provide contributions, read the [CONTRIBUTING](CONTRIBUTING.md) doc.
---
diff --git a/bin/helper/mezzio-swoole b/bin/helper/mezzio-swoole
new file mode 100755
index 00000000..2c341326
--- /dev/null
+++ b/bin/helper/mezzio-swoole
@@ -0,0 +1,51 @@
+#!/usr/bin/env php
+get('config')['laminas-cli']['commands'] ?? [],
+ fn ($c, string $command) => str_starts_with($command, $commandsPrefix),
+);
+$registeredCommands = [];
+
+foreach ($commands as $newName => $commandServiceName) {
+ [, $oldName] = explode($commandsPrefix, $newName);
+ $registeredCommands[$oldName] = $commandServiceName;
+
+ $container->addDelegator($commandServiceName, static function ($c, $n, callable $factory) use ($oldName) {
+ /** @var Command $command */
+ $command = $factory();
+ $command->setAliases([$oldName]);
+
+ return $command;
+ });
+}
+
+$commandLine = new CommandLine('Mezzio web server', $version);
+$commandLine->setAutoExit(true);
+$commandLine->setCommandLoader(new ContainerCommandLoader($container, $registeredCommands));
+$commandLine->run();
diff --git a/bin/set-option b/bin/set-option
new file mode 100755
index 00000000..ff727f30
--- /dev/null
+++ b/bin/set-option
@@ -0,0 +1,14 @@
+#!/usr/bin/env php
+Alias for \"cs\", \"stan\", \"test:ci\" and \"infect:ci\">",
+ "ci:parallel": "Same as \"ci\", but parallelizing tasks as much as possible>",
"cs": "Checks coding styles>",
"cs:fix": "Fixes coding styles, when possible>",
"stan": "Inspects code with phpstan>",
@@ -160,14 +156,17 @@
"test:unit:ci": "Runs unit test suites, generating all needed reports and logs for CI envs>",
"test:db": "Runs database test suites on a SQLite, MySQL, MariaDB, PostgreSQL and MsSQL>",
"test:db:sqlite": "Runs database test suites on a SQLite database>",
+ "test:db:sqlite:ci": "Runs database test suites on a SQLite database, generating all needed reports and logs for CI envs>",
"test:db:mysql": "Runs database test suites on a MySQL database>",
"test:db:maria": "Runs database test suites on a MariaDB database>",
"test:db:postgres": "Runs database test suites on a PostgreSQL database>",
+ "test:db:ms": "Runs database test suites on a Miscrosoft SQL Server database>",
"test:api": "Runs API test suites>",
"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>",
- "infect:test": "Checks unit tests quality applying mutation testing>",
+ "infect:ci": "Checks unit and db tests quality applying mutation testing with existing reports and logs>",
+ "infect:ci:unit": "Checks unit tests quality applying mutation testing with existing reports and logs>",
+ "infect:ci:db": "Checks db tests quality applying mutation testing with existing reports and logs>",
+ "infect:test": "Runs unit and db tests, then checks tests quality applying mutation testing>",
"clean:dev": "Deletes artifacts which are gitignored and could affect dev env>"
},
"config": {
diff --git a/config/autoload/cors.global.php b/config/autoload/cors.global.php
new file mode 100644
index 00000000..58ad9428
--- /dev/null
+++ b/config/autoload/cors.global.php
@@ -0,0 +1,11 @@
+ [
+ 'max_age' => 3600,
+ ],
+
+];
diff --git a/config/autoload/entity-manager.global.php b/config/autoload/entity-manager.global.php
index c08f66f2..639df7ec 100644
--- a/config/autoload/entity-manager.global.php
+++ b/config/autoload/entity-manager.global.php
@@ -4,12 +4,15 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Common;
+use Happyr\DoctrineSpecification\EntitySpecificationRepository;
+
return [
'entity_manager' => [
'orm' => [
'proxies_dir' => 'data/proxies',
'load_mappings_using_functional_style' => true,
+ 'default_repository_classname' => EntitySpecificationRepository::class,
],
'connection' => [
'user' => '',
diff --git a/config/autoload/installer.global.php b/config/autoload/installer.global.php
index ba0b8332..a04d874b 100644
--- a/config/autoload/installer.global.php
+++ b/config/autoload/installer.global.php
@@ -14,6 +14,7 @@ return [
Option\Database\DatabasePortConfigOption::class,
Option\Database\DatabaseUserConfigOption::class,
Option\Database\DatabasePasswordConfigOption::class,
+ Option\Database\DatabaseUnixSocketConfigOption::class,
Option\Database\DatabaseSqlitePathConfigOption::class,
Option\Database\DatabaseMySqlOptionsConfigOption::class,
Option\UrlShortener\ShortDomainHostConfigOption::class,
diff --git a/config/autoload/templates.global.php b/config/autoload/templates.global.php
deleted file mode 100644
index e1b457fa..00000000
--- a/config/autoload/templates.global.php
+++ /dev/null
@@ -1,17 +0,0 @@
- [
- 'extension' => 'phtml',
- ],
-
- 'plates' => [
- 'extensions' => [
- // extension service names or instances
- ],
- ],
-
-];
diff --git a/config/config.php b/config/config.php
index ba0657fc..cf9eb86b 100644
--- a/config/config.php
+++ b/config/config.php
@@ -15,7 +15,6 @@ return (new ConfigAggregator\ConfigAggregator([
Mezzio\ConfigProvider::class,
Mezzio\Router\ConfigProvider::class,
Mezzio\Router\FastRouteRouter\ConfigProvider::class,
- Mezzio\Plates\ConfigProvider::class,
Mezzio\Swoole\ConfigProvider::class,
ProblemDetails\ConfigProvider::class,
Diactoros\ConfigProvider::class,
diff --git a/config/test/test_config.global.php b/config/test/test_config.global.php
index 6b3c6612..3608257e 100644
--- a/config/test/test_config.global.php
+++ b/config/test/test_config.global.php
@@ -36,7 +36,7 @@ if ($isApiTest) {
$buildDbConnection = function (): array {
$driver = env('DB_DRIVER', 'sqlite');
- $isCi = env('TRAVIS', false);
+ $isCi = env('CI', false);
$getMysqlHost = fn (string $driver) => sprintf('shlink_db%s', $driver === 'mysql' ? '' : '_maria');
$getCiMysqlPort = fn (string $driver) => $driver === 'mysql' ? '3307' : '3308';
diff --git a/data/infra/ci/install-ms-odbc.sh b/data/infra/ci/install-ms-odbc.sh
index 8cd60580..1efdf8a3 100755
--- a/data/infra/ci/install-ms-odbc.sh
+++ b/data/infra/ci/install-ms-odbc.sh
@@ -3,7 +3,7 @@
set -ex
curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
-curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
+curl https://packages.microsoft.com/config/ubuntu/20.04/prod.list > /etc/apt/sources.list.d/mssql-release.list
apt-get update
ACCEPT_EULA=Y apt-get install msodbcsql17
apt-get install unixodbc-dev
diff --git a/data/infra/examples/shlink-daemon.sh b/data/infra/examples/shlink-daemon.sh
index a18ca65a..ce905721 100644
--- a/data/infra/examples/shlink-daemon.sh
+++ b/data/infra/examples/shlink-daemon.sh
@@ -8,7 +8,7 @@
# Description: Shlink non-blocking server with swoole
### END INIT INFO
-SCRIPT=/path/to/shlink/vendor/bin/mezzio-swoole\ start
+SCRIPT=/path/to/shlink/vendor/bin/laminas\ mezzio:swoole:start
RUNAS=root
PIDFILE=/var/run/shlink_swoole.pid
diff --git a/data/infra/swoole.Dockerfile b/data/infra/swoole.Dockerfile
index 00d197ba..bb1f084c 100644
--- a/data/infra/swoole.Dockerfile
+++ b/data/infra/swoole.Dockerfile
@@ -4,7 +4,7 @@ MAINTAINER Alejandro Celaya
ENV APCU_VERSION 5.1.18
ENV APCU_BC_VERSION 1.0.5
ENV INOTIFY_VERSION 2.0.0
-ENV SWOOLE_VERSION 4.5.5
+ENV SWOOLE_VERSION 4.5.9
RUN apk update
@@ -95,4 +95,4 @@ CMD \
if [[ ! -d "./vendor" ]]; then /usr/local/bin/composer install ; fi && \
# When restarting the container, swoole might think it is already in execution
# This forces the app to be started every second until the exit code is 0
- until php ./vendor/bin/mezzio-swoole start; do sleep 1 ; done
+ until php ./vendor/bin/laminas mezzio:swoole:start; do sleep 1 ; done
diff --git a/data/migrations/Version20180913205455.php b/data/migrations/Version20180913205455.php
index 8afa316b..c2bc2070 100644
--- a/data/migrations/Version20180913205455.php
+++ b/data/migrations/Version20180913205455.php
@@ -58,7 +58,7 @@ final class Version20180913205455 extends AbstractMigration
}
try {
- return (string) IpAddress::fromString($addr)->getObfuscatedCopy();
+ return (string) IpAddress::fromString($addr)->getAnonymizedCopy();
} catch (InvalidArgumentException $e) {
return null;
}
diff --git a/data/migrations/Version20210102174433.php b/data/migrations/Version20210102174433.php
new file mode 100644
index 00000000..95ee62fe
--- /dev/null
+++ b/data/migrations/Version20210102174433.php
@@ -0,0 +1,52 @@
+skipIf($schema->hasTable(self::TABLE_NAME));
+
+ $table = $schema->createTable(self::TABLE_NAME);
+ $table->addColumn('id', Types::BIGINT, [
+ 'unsigned' => true,
+ 'autoincrement' => true,
+ 'notnull' => true,
+ ]);
+ $table->setPrimaryKey(['id']);
+
+ $table->addColumn('role_name', Types::STRING, [
+ 'length' => 256,
+ 'notnull' => true,
+ ]);
+ $table->addColumn('meta', Types::JSON, [
+ 'notnull' => true,
+ ]);
+
+ $table->addColumn('api_key_id', Types::BIGINT, [
+ 'unsigned' => true,
+ 'notnull' => true,
+ ]);
+ $table->addForeignKeyConstraint('api_keys', ['api_key_id'], ['id'], [
+ 'onDelete' => 'CASCADE',
+ 'onUpdate' => 'RESTRICT',
+ ]);
+ $table->addUniqueIndex(['role_name', 'api_key_id'], 'UQ_role_plus_api_key');
+ }
+
+ public function down(Schema $schema): void
+ {
+ $this->skipIf(! $schema->hasTable(self::TABLE_NAME));
+ $schema->getTable(self::TABLE_NAME)->dropIndex('UQ_role_plus_api_key');
+ $schema->dropTable(self::TABLE_NAME);
+ }
+}
diff --git a/docker-compose.yml b/docker-compose.yml
index d700f3b3..ba4558e4 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -131,7 +131,7 @@ services:
shlink_mercure:
container_name: shlink_mercure
- image: dunglas/mercure:v0.9
+ image: dunglas/mercure:v0.10
ports:
- "3080:80"
environment:
diff --git a/docker/README.md b/docker/README.md
index 2cc0b5b9..5269ebb6 100644
--- a/docker/README.md
+++ b/docker/README.md
@@ -1,76 +1,21 @@
# Shlink Docker image
-[](https://hub.docker.com/r/shlinkio/shlink/)
+[](https://github.com/shlinkio/shlink/actions?query=workflow%3A%22Build+docker+image%22)
+[](https://hub.docker.com/r/shlinkio/shlink/)
This image provides an easy way to set up [shlink](https://shlink.io) on a container-based runtime.
-It exposes a shlink instance served with [swoole](https://www.swoole.co.uk/), which persists data in a local [sqlite](https://www.sqlite.org/index.html) database.
+It exposes a shlink instance served with [swoole](https://www.swoole.co.uk/), which can be linked to external databases to persist data.
## Usage
-Shlink docker image exposes port `8080` in order to interact with its HTTP interface.
-
-It also expects these two env vars to be provided, in order to properly generate short URLs at runtime.
+The most basic way to run Shlink's docker image is by providing these mandatory env vars.
* `SHORT_DOMAIN_HOST`: The custom short domain used for this shlink instance. For example **doma.in**.
* `SHORT_DOMAIN_SCHEMA`: Either **http** or **https**.
+* `GEOLITE_LICENSE_KEY`: Your GeoLite2 license key. [Learn more](https://shlink.io/documentation/geolite-license-key/) about this.
-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 -e GEOLITE_LICENSE_KEY=kjh23ljkbndskj345 shlinkio/shlink:stable
-```
-
-### Interact with shlink's CLI on a running container.
-
-Once the shlink container is running, you can interact with the CLI tool by running `shlink` with any of the supported commands.
-
-For example, if the container is called `shlink_container`, you can generate a new API key with:
-
-```bash
-docker exec -it shlink_container shlink api-key:generate
-```
-
-Or you can list all tags with:
-
-```bash
-docker exec -it shlink_container shlink tag:list
-```
-
-Or locate remaining visits with:
-
-```bash
-docker exec -it shlink_container shlink visit:locate
-```
-
-All shlink commands will work the same way.
-
-You can also list all available commands just by running this:
-
-```bash
-docker exec -it shlink_container shlink
-```
-
-## Use an external DB
-
-The image comes with a working sqlite database, but in production you will probably want to usa a distributed database.
-
-It is possible to use a set of env vars to make this shlink instance interact with an external MySQL, MariaDB, PostgreSQL or Microsoft SQL Server database.
-
-* `DB_DRIVER`: **[Mandatory]**. Use the value **mysql**, **maria**, **postgres** or **mssql** to prevent the sqlite database to be used.
-* `DB_NAME`: [Optional]. The database name to be used. Defaults to **shlink**.
-* `DB_USER`: **[Mandatory]**. The username credential for the database server.
-* `DB_PASSWORD`: **[Mandatory]**. The password credential for the database server.
-* `DB_HOST`: **[Mandatory]**. The host name of the server running the database engine.
-* `DB_PORT`: [Optional]. The port in which the database service is running.
- * Default value is based on the value provided for `DB_DRIVER`:
- * **mysql** or **maria** -> `3306`
- * **postgres** -> `5432`
- * **mssql** -> `1433`
-
-> PostgreSQL is supported since v1.16.1 and Microsoft SQL server since v2.1.0. Do not try to use them with previous versions.
-
-Taking this into account, you could run shlink on a local docker service like this:
+To run shlink on top of a local docker service, and using an internal SQLite database, do the following:
```bash
docker run \
@@ -78,222 +23,12 @@ docker run \
-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: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.
-
-## Other integrations
-
-### Use an external redis server
-
-If you plan to run more than one Shlink instance, there are some resources that should be shared ([Multi instance considerations](#multi-instance-considerations)).
-
-One of those resources are the locks Shlink generates to prevent some operations to be run more than once in parallel (in the future, these redis servers could be used for other caching operations).
-
-In order to share those locks, you should use an external redis server (or a cluster of redis servers), by providing the `REDIS_SERVERS` env var.
-
-It can be either one server name or a comma-separated list of servers.
-
-> If more than one redis server is provided, Shlink will expect them to be configured as a [redis cluster](https://redis.io/topics/cluster-tutorial).
-
-### Integrate with a mercure hub server
-
-One way to get real time updates when certain events happen in Shlink is by integrating it with a [mercure hub](https://mercure.rocks/) server.
-
-If you do that, Shlink will publish updates and other clients can subscribe to those.
-
-There are three env vars you need to provide if you want to enable this:
-
-* `MERCURE_PUBLIC_HUB_URL`: **[Mandatory]**. The public URL of a mercure hub server to which Shlink will sent updates. This URL will also be served to consumers that want to subscribe to those updates.
-* `MERCURE_INTERNAL_HUB_URL`: **[Optional]**. An internal URL for a mercure hub. Will be used only when publishing updates to mercure, and does not need to be public. If this is not provided, the `MERCURE_PUBLIC_HUB_URL` one will be used to publish updates.
-* `MERCURE_JWT_SECRET`: **[Mandatory]**. The secret key that was provided to the mercure hub server, in order to be able to generate valid JWTs for publishing/subscribing to that server.
-
-So in order to run shlink with mercure integration, you would do it like this:
-
-```bash
-docker run \
- --name shlink \
- -p 8080:8080 \
- -e SHORT_DOMAIN_HOST=doma.in \
- -e SHORT_DOMAIN_SCHEMA=https \
- -e "MERCURE_PUBLIC_HUB_URL=https://example.com"
- -e "MERCURE_INTERNAL_HUB_URL=http://my-mercure-hub.prod.svc.cluster.local"
- -e MERCURE_JWT_SECRET=super_secret_key
- shlinkio/shlink:stable
-```
-
-## All supported env vars
-
-A few env vars have been already used in previous examples, but this image supports others that can be used to customize its behavior.
-
-This is the complete list of supported env vars:
-
-* `SHORT_DOMAIN_HOST`: The custom short domain used for this shlink instance. For example **doma.in**.
-* `SHORT_DOMAIN_SCHEMA`: Either **http** or **https**.
-* `DB_DRIVER`: **sqlite** (which is the default value), **mysql**, **maria**, **postgres** or **mssql**.
-* `DB_NAME`: The database name to be used when using an external database driver. Defaults to **shlink**.
-* `DB_USER`: The username credential to be used when using an external database driver.
-* `DB_PASSWORD`: The password credential to be used when using an external database driver.
-* `DB_HOST`: The host name of the database server when using an external database driver.
-* `DB_PORT`: The port in which the database service is running when using an external database driver.
- * Default value is based on the value provided for `DB_DRIVER`:
- * **mysql** or **maria** -> `3306`
- * **postgres** -> `5432`
- * **mssql** -> `1433`
-* `DISABLE_TRACK_PARAM`: The name of a query param that can be used to visit short URLs avoiding the visit to be tracked. This feature won't be available if not value is provided.
-* `DELETE_SHORT_URL_THRESHOLD`: The amount of visits on short URLs which will not allow them to be deleted. Defaults to `15`.
-* `VALIDATE_URLS`: Boolean which tells if shlink should validate a status 20x is returned (after following redirects) when trying to shorten a URL. Defaults to `false`.
-* `INVALID_SHORT_URL_REDIRECT_TO`: If a URL is provided here, when a user tries to access an invalid short URL, he/she will be redirected to this value. If this env var is not provided, the user will see a generic `404 - not found` page.
-* `REGULAR_404_REDIRECT_TO`: If a URL is provided here, when a user tries to access a URL not matching any one supported by the router, he/she will be redirected to this value. If this env var is not provided, the user will see a generic `404 - not found` page.
-* `BASE_URL_REDIRECT_TO`: If a URL is provided here, when a user tries to access Shlink's base URL, he/she will be redirected to this value. If this env var is not provided, the user will see a generic `404 - not found` page.
-* `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.
-* `DEFAULT_SHORT_CODES_LENGTH`: The length you want generated short codes to have. It defaults to 5 and has to be at least 4, so any value smaller than that will fall back to 4.
-* `GEOLITE_LICENSE_KEY`: The license key used to download new GeoLite2 database files. This is not mandatory, as a default license key is provided, but it is **strongly recommended** that you provide your own. Go to [https://shlink.io/documentation/geolite-license-key](https://shlink.io/documentation/geolite-license-key) to know how to generate it.
-* `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).
-* `MERCURE_PUBLIC_HUB_URL`: The public URL of a mercure hub server to which Shlink will sent updates. This URL will also be served to consumers that want to subscribe to those updates.
-* `MERCURE_INTERNAL_HUB_URL`: An internal URL for a mercure hub. Will be used only when publishing updates to mercure, and does not need to be public. If this is not provided but `MERCURE_PUBLIC_HUB_URL` was, the former one will be used to publish updates.
-* `MERCURE_JWT_SECRET`: The secret key that was provided to the mercure hub server, in order to be able to generate valid JWTs for publishing/subscribing to that server.
-* `ANONYMIZE_REMOTE_ADDR`: Tells if IP addresses from visitors should be obfuscated before storing them in the database. Default value is `true`. **Careful!** Setting this to `false` will make your Shlink instance no longer be in compliance with the GDPR and other similar data protection regulations.
-* `REDIRECT_STATUS_CODE`: Either **301** or **302**. Used to determine if redirects from short to long URLs should be done with a 301 or 302 status. Defaults to 302.
-* `REDIRECT_CACHE_LIFETIME`: Allows to set the amount of seconds that redirects should be cached when redirect status is 301. Default values is 30.
-* `PORT`: Can be used to set the port in which shlink listens. Defaults to 8080 (Some cloud providers, like Google cloud or Heroku, expect to be able to customize exposed port by providing this env var).
-
-An example using all env vars could look like this:
-
-```bash
-docker run \
- --name shlink \
- -p 8080:8888 \
- -e SHORT_DOMAIN_HOST=doma.in \
- -e SHORT_DOMAIN_SCHEMA=https \
- -e PORT=8888 \
- -e DB_DRIVER=mysql \
- -e DB_NAME=shlink \
- -e DB_USER=root \
- -e DB_PASSWORD=123abc \
- -e DB_HOST=something.rds.amazonaws.com \
- -e DB_PORT=3306 \
- -e DISABLE_TRACK_PARAM="no-track" \
- -e DELETE_SHORT_URL_THRESHOLD=30 \
- -e VALIDATE_URLS=true \
- -e "INVALID_SHORT_URL_REDIRECT_TO=https://my-landing-page.com" \
- -e "REGULAR_404_REDIRECT_TO=https://my-landing-page.com" \
- -e "BASE_URL_REDIRECT_TO=https://my-landing-page.com" \
- -e "REDIS_SERVERS=tcp://172.20.0.1:6379,tcp://172.20.0.2:6379" \
- -e "BASE_PATH=/my-campaign" \
- -e WEB_WORKER_NUM=64 \
- -e TASK_WORKER_NUM=32 \
- -e "VISITS_WEBHOOKS=http://my-api.com/api/v2.3/notify,https://third-party.io/foo" \
- -e DEFAULT_SHORT_CODES_LENGTH=6 \
-e GEOLITE_LICENSE_KEY=kjh23ljkbndskj345 \
- -e "MERCURE_PUBLIC_HUB_URL=https://example.com" \
- -e "MERCURE_INTERNAL_HUB_URL=http://my-mercure-hub.prod.svc.cluster.local" \
- -e MERCURE_JWT_SECRET=super_secret_key \
- -e ANONYMIZE_REMOTE_ADDR=false \
- -e REDIRECT_STATUS_CODE=301 \
- -e REDIRECT_CACHE_LIFETIME=90 \
shlinkio/shlink:stable
```
-## Provide config via volumes
+## Full documentation
-Rather than providing custom configuration via env vars, it is also possible ot provide config files in json format.
+All the features supported by Shlink are also supported by the docker image.
-Mounting a volume at `config/params` you will make shlink load all the files on it with the `.config.json` suffix.
-
-The whole configuration should have this format, but it can be split into multiple files that will be merged:
-
-```json
-{
- "disable_track_param": "my_param",
- "delete_short_url_threshold": 30,
- "short_domain_schema": "https",
- "short_domain_host": "doma.in",
- "validate_url": true,
- "invalid_short_url_redirect_to": "https://my-landing-page.com",
- "regular_404_redirect_to": "https://my-landing-page.com",
- "base_url_redirect_to": "https://my-landing-page.com",
- "base_path": "/my-campaign",
- "web_worker_num": 64,
- "task_worker_num": 32,
- "default_short_codes_length": 6,
- "redis_servers": [
- "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",
- "user": "root",
- "password": "123abc",
- "host": "something.rds.amazonaws.com",
- "port": "3306"
- },
- "geolite_license_key": "kjh23ljkbndskj345",
- "mercure_public_hub_url": "https://example.com",
- "mercure_internal_hub_url": "http://my-mercure-hub.prod.svc.cluster.local",
- "mercure_jwt_secret": "super_secret_key",
- "anonymize_remote_addr": false,
- "redirect_status_code": 301,
- "redirect_cache_lifetime": 90,
- "port": 8888
-}
-```
-
-> This is internally parsed to how shlink expects the config. If you are using a version previous to 1.17.0, this parser is not present and you need to provide a config structure like the one [documented previously](https://github.com/shlinkio/shlink-docker-image/tree/v1.16.3#provide-config-via-volumes).
-
-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:stable
-```
-
-## Multi-architecture
-
-Starting on v2.3.0, Shlink's docker image is built for multiple architectures.
-
-The only limitation is that images for architectures other than `amd64` will not have support for Microsoft SQL databases, since there are no official binaries.
-
-## Multi-instance considerations
-
-These are some considerations to take into account when running multiple instances of shlink.
-
-* Some operations performed by Shlink should never be run more than once at the same time (like creating the database for the first time, or downloading the GeoLite2 database). For this reason, Shlink uses a locking system.
-
- However, these locks are locally scoped to each Shlink instance by default.
-
- You can (and should) make the locks to be shared by all Shlink instances by using a redis server/cluster. Just define the `REDIS_SERVERS` env var with the list of servers.
-
-## Versions
-
-Versioning on this docker image works as follows:
-
-* `X.X.X`: when providing a specific version number, the image version will match the shlink version it contains. For example, installing `shlinkio/shlink:1.15.0`, you will get an image containing shlink v1.15.0.
-* `stable`: always holds the latest stable tag. For example, if latest shlink version is 2.0.0, installing `shlinkio/shlink:stable`, you will get an image containing shlink v2.0.0
-* `latest`: always holds the latest contents, and it's considered unstable and not suitable for production.
-
-> **Important**: The docker image was introduced with shlink v1.15.0, so there are no official images previous to that versions.
+If you want to learn more, visit the [full documentation](https://shlink.io/documentation/install-docker-image/).
diff --git a/docker/config/shlink_in_docker.local.php b/docker/config/shlink_in_docker.local.php
index c4502b7c..c6d7f69e 100644
--- a/docker/config/shlink_in_docker.local.php
+++ b/docker/config/shlink_in_docker.local.php
@@ -34,6 +34,7 @@ $helper = new class {
public function getDbConfig(): array
{
$driver = env('DB_DRIVER');
+ $isMysql = contains(['maria', 'mysql'], $driver);
if ($driver === null || $driver === 'sqlite') {
return [
'driver' => 'pdo_sqlite',
@@ -41,7 +42,7 @@ $helper = new class {
];
}
- $driverOptions = ! contains(['maria', 'mysql'], $driver) ? [] : [
+ $driverOptions = ! $isMysql ? [] : [
// 1002 -> PDO::MYSQL_ATTR_INIT_COMMAND
1002 => 'SET NAMES utf8',
// 1000 -> PDO::MYSQL_ATTR_USE_BUFFERED_QUERY
@@ -52,9 +53,10 @@ $helper = new class {
'dbname' => env('DB_NAME', 'shlink'),
'user' => env('DB_USER'),
'password' => env('DB_PASSWORD'),
- 'host' => env('DB_HOST'),
+ 'host' => env('DB_HOST', $driver === 'postgres' ? env('DB_UNIX_SOCKET') : null),
'port' => env('DB_PORT', self::DB_PORTS_MAP[$driver]),
'driverOptions' => $driverOptions,
+ 'unix_socket' => $isMysql ? env('DB_UNIX_SOCKET') : null,
];
}
diff --git a/docker/docker-entrypoint.sh b/docker/docker-entrypoint.sh
index 055e315f..df480d2f 100644
--- a/docker/docker-entrypoint.sh
+++ b/docker/docker-entrypoint.sh
@@ -17,4 +17,4 @@ php vendor/doctrine/orm/bin/doctrine.php orm:clear-cache:metadata -n -q
# When restarting the container, swoole might think it is already in execution
# This forces the app to be started every second until the exit code is 0
-until php vendor/mezzio/mezzio-swoole/bin/mezzio-swoole start; do sleep 1 ; done
+until php vendor/bin/laminas mezzio:swoole:start; do sleep 1 ; done
diff --git a/docs/swagger/paths/v1_short-urls.json b/docs/swagger/paths/v1_short-urls.json
index a89dd187..a81853d8 100644
--- a/docs/swagger/paths/v1_short-urls.json
+++ b/docs/swagger/paths/v1_short-urls.json
@@ -191,7 +191,7 @@
"Short URLs"
],
"summary": "Create short URL",
- "description": "Creates a new short URL. **Param findIfExists:**: Starting with v1.16, this new param allows to force shlink to return existing short URLs when found based on provided params, instead of creating a new one. However, it might add complexity and have unexpected outputs.\n\nThese are the use cases:\n* Only the long URL is provided: It will return the newest match or create a new short URL if none is found.\n* Long url and custom slug are provided: It will return the short URL when both params match, return an error when the slug is in use for another long URL, or create a new short URL otherwise.\n* Any of the above but including other params (tags, validSince, validUntil, maxVisits): It will behave the same as the previous two cases, but it will try to exactly match existing results using all the params. If any of them does not match, it will try to create a new short URL.",
+ "description": "Creates a new short URL. **Param findIfExists**: This new param allows to force shlink to return existing short URLs when found based on provided params, instead of creating a new one. However, it might add complexity and have unexpected outputs.\n\nThese are the use cases:\n* Only the long URL is provided: It will return the newest match or create a new short URL if none is found.\n* Long url and custom slug are provided: It will return the short URL when both params match, return an error when the slug is in use for another long URL, or create a new short URL otherwise.\n* Any of the above but including other params (tags, validSince, validUntil, maxVisits): It will behave the same as the previous two cases, but it will try to exactly match existing results using all the params. If any of them does not match, it will try to create a new short URL.",
"security": [
{
"ApiKey": []
diff --git a/docs/swagger/paths/v1_tags.json b/docs/swagger/paths/v1_tags.json
index cb6a6bb3..8c3ada73 100644
--- a/docs/swagger/paths/v1_tags.json
+++ b/docs/swagger/paths/v1_tags.json
@@ -232,6 +232,16 @@
}
}
},
+ "403": {
+ "description": "The API key you used does not have permissions to rename tags.",
+ "content": {
+ "application/problem+json": {
+ "schema": {
+ "$ref": "../definitions/Error.json"
+ }
+ }
+ }
+ },
"404": {
"description": "There's no tag found with the name provided in oldName param.",
"content": {
@@ -298,6 +308,16 @@
"204": {
"description": "Tags properly deleted"
},
+ "403": {
+ "description": "The API key you used does not have permissions to delete tags.",
+ "content": {
+ "application/problem+json": {
+ "schema": {
+ "$ref": "../definitions/Error.json"
+ }
+ }
+ }
+ },
"500": {
"description": "Unexpected error.",
"content": {
diff --git a/docs/swagger/paths/{shortCode}_qr-code.json b/docs/swagger/paths/{shortCode}_qr-code.json
index a3fdaffb..3714f802 100644
--- a/docs/swagger/paths/{shortCode}_qr-code.json
+++ b/docs/swagger/paths/{shortCode}_qr-code.json
@@ -18,7 +18,7 @@
},
{
"name": "size",
- "in": "path",
+ "in": "query",
"description": "The size of the image to be returned.",
"required": false,
"schema": {
diff --git a/docs/swagger/paths/{shortCode}_qr-code_{size}.json b/docs/swagger/paths/{shortCode}_qr-code_{size}.json
new file mode 100644
index 00000000..fb5dd33e
--- /dev/null
+++ b/docs/swagger/paths/{shortCode}_qr-code_{size}.json
@@ -0,0 +1,66 @@
+{
+ "get": {
+ "operationId": "shortUrlQrCodeSize",
+ "deprecated": true,
+ "tags": [
+ "URL Shortener"
+ ],
+ "summary": "Short URL QR code",
+ "description": "Generates a QR code image pointing to a short URL",
+ "parameters": [
+ {
+ "name": "shortCode",
+ "in": "path",
+ "description": "The short code to resolve.",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "size",
+ "in": "path",
+ "description": "The size of the image to be returned.",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "minimum": 50,
+ "maximum": 1000,
+ "default": 300
+ }
+ },
+ {
+ "name": "format",
+ "in": "query",
+ "description": "The format for the QR code image, being valid values png and svg. Not providing the param or providing any other value will fall back to png.",
+ "required": false,
+ "schema": {
+ "type": "string",
+ "enum": [
+ "png",
+ "svg"
+ ]
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "QR code in PNG format",
+ "content": {
+ "image/png": {
+ "schema": {
+ "type": "string",
+ "format": "binary"
+ }
+ },
+ "image/svg+xml": {
+ "schema": {
+ "type": "string",
+ "format": "binary"
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/docs/swagger/swagger.json b/docs/swagger/swagger.json
index 8dc04412..dc834905 100644
--- a/docs/swagger/swagger.json
+++ b/docs/swagger/swagger.json
@@ -116,6 +116,9 @@
},
"/{shortCode}/qr-code": {
"$ref": "paths/{shortCode}_qr-code.json"
+ },
+ "/{shortCode}/qr-code/{size}": {
+ "$ref": "paths/{shortCode}_qr-code_{size}.json"
}
}
}
diff --git a/infection-db.json b/infection-db.json
new file mode 100644
index 00000000..a429c995
--- /dev/null
+++ b/infection-db.json
@@ -0,0 +1,23 @@
+{
+ "source": {
+ "directories": [
+ "module/*/src"
+ ]
+ },
+ "timeout": 5,
+ "logs": {
+ "text": "build/infection-db/infection-log.txt",
+ "summary": "build/infection-db/summary-log.txt",
+ "debug": "build/infection-db/debug-log.txt"
+ },
+ "tmpDir": "build/infection-db/temp",
+ "phpUnit": {
+ "configDir": "."
+ },
+ "testFrameworkOptions": "--configuration=phpunit-db.xml",
+ "mutators": {
+ "@default": true,
+ "IdenticalEqual": false,
+ "NotIdenticalNotEqual": false
+ }
+}
diff --git a/infection.json b/infection.json
index 44fdf228..b182bddf 100644
--- a/infection.json
+++ b/infection.json
@@ -6,11 +6,11 @@
},
"timeout": 5,
"logs": {
- "text": "build/infection/infection-log.txt",
- "summary": "build/infection/summary-log.txt",
- "debug": "build/infection/debug-log.txt"
+ "text": "build/infection-unit/infection-log.txt",
+ "summary": "build/infection-unit/summary-log.txt",
+ "debug": "build/infection-unit/debug-log.txt"
},
- "tmpDir": "build/infection/temp",
+ "tmpDir": "build/infection-unit/temp",
"phpUnit": {
"configDir": "."
},
diff --git a/module/CLI/config/dependencies.config.php b/module/CLI/config/dependencies.config.php
index 199d29ef..3c9d74ce 100644
--- a/module/CLI/config/dependencies.config.php
+++ b/module/CLI/config/dependencies.config.php
@@ -8,7 +8,6 @@ use Doctrine\DBAL\Connection;
use GeoIp2\Database\Reader;
use Laminas\ServiceManager\AbstractFactory\ConfigAbstractFactory;
use Laminas\ServiceManager\Factory\InvokableFactory;
-use Shlinkio\Shlink\CLI\Util\GeolocationDbUpdater;
use Shlinkio\Shlink\Common\Doctrine\NoDbNameConnectionFactory;
use Shlinkio\Shlink\Core\Domain\DomainService;
use Shlinkio\Shlink\Core\Service;
@@ -32,7 +31,8 @@ return [
SymfonyCli\Helper\ProcessHelper::class => ProcessHelperFactory::class,
PhpExecutableFinder::class => InvokableFactory::class,
- GeolocationDbUpdater::class => ConfigAbstractFactory::class,
+ Util\GeolocationDbUpdater::class => ConfigAbstractFactory::class,
+ ApiKey\RoleResolver::class => ConfigAbstractFactory::class,
Command\ShortUrl\GenerateShortUrlCommand::class => ConfigAbstractFactory::class,
Command\ShortUrl\ResolveUrlCommand::class => ConfigAbstractFactory::class,
@@ -59,7 +59,8 @@ return [
],
ConfigAbstractFactory::class => [
- GeolocationDbUpdater::class => [DbUpdater::class, Reader::class, LOCAL_LOCK_FACTORY],
+ Util\GeolocationDbUpdater::class => [DbUpdater::class, Reader::class, LOCAL_LOCK_FACTORY],
+ ApiKey\RoleResolver::class => [DomainService::class],
Command\ShortUrl\GenerateShortUrlCommand::class => [
Service\UrlShortener::class,
@@ -75,10 +76,10 @@ return [
Visit\VisitLocator::class,
IpLocationResolverInterface::class,
LockFactory::class,
- GeolocationDbUpdater::class,
+ Util\GeolocationDbUpdater::class,
],
- Command\Api\GenerateKeyCommand::class => [ApiKeyService::class],
+ Command\Api\GenerateKeyCommand::class => [ApiKeyService::class, ApiKey\RoleResolver::class],
Command\Api\DisableKeyCommand::class => [ApiKeyService::class],
Command\Api\ListKeysCommand::class => [ApiKeyService::class],
@@ -87,7 +88,7 @@ return [
Command\Tag\RenameTagCommand::class => [TagService::class],
Command\Tag\DeleteTagsCommand::class => [TagService::class],
- Command\Domain\ListDomainsCommand::class => [DomainService::class, 'config.url_shortener.domain.hostname'],
+ Command\Domain\ListDomainsCommand::class => [DomainService::class],
Command\Db\CreateDatabaseCommand::class => [
LockFactory::class,
diff --git a/module/CLI/src/ApiKey/RoleResolver.php b/module/CLI/src/ApiKey/RoleResolver.php
new file mode 100644
index 00000000..67747983
--- /dev/null
+++ b/module/CLI/src/ApiKey/RoleResolver.php
@@ -0,0 +1,36 @@
+domainService = $domainService;
+ }
+
+ public function determineRoles(InputInterface $input): array
+ {
+ $domainAuthority = $input->getOption('domain-only');
+ $author = $input->getOption('author-only');
+
+ $roleDefinitions = [];
+ if ($author) {
+ $roleDefinitions[] = RoleDefinition::forAuthoredShortUrls();
+ }
+ if ($domainAuthority !== null) {
+ $domain = $this->domainService->getOrCreate($domainAuthority);
+ $roleDefinitions[] = RoleDefinition::forDomain($domain);
+ }
+
+ return $roleDefinitions;
+ }
+}
diff --git a/module/CLI/src/ApiKey/RoleResolverInterface.php b/module/CLI/src/ApiKey/RoleResolverInterface.php
new file mode 100644
index 00000000..98d50483
--- /dev/null
+++ b/module/CLI/src/ApiKey/RoleResolverInterface.php
@@ -0,0 +1,19 @@
+apiKeyService = $apiKeyService;
parent::__construct();
+ $this->apiKeyService = $apiKeyService;
+ $this->roleResolver = $roleResolver;
}
protected function configure(): void
{
+ $authorOnly = RoleResolverInterface::AUTHOR_ONLY_PARAM;
+ $domainOnly = RoleResolverInterface::DOMAIN_ONLY_PARAM;
+ $help = <<%command.name% generates a new valid API key.
+
+ %command.full_name%
+
+ You can optionally set its expiration date with --expirationDate or -e:
+
+ %command.full_name% --expirationDate 2020-01-01
+
+ You can also set roles to the API key:
+
+ * Can interact with short URLs created with this API key: %command.full_name% --{$authorOnly}
+ * Can interact with short URLs for one domain: %command.full_name% --{$domainOnly}=example.com
+ * Both: %command.full_name% --{$authorOnly} --{$domainOnly}=example.com
+ HELP;
+
$this
->setName(self::NAME)
->setDescription('Generates a new valid API key.')
@@ -37,15 +61,42 @@ class GenerateKeyCommand extends Command
'e',
InputOption::VALUE_REQUIRED,
'The date in which the API key should expire. Use any valid PHP format.',
- );
+ )
+ ->addOption(
+ $authorOnly,
+ 'a',
+ InputOption::VALUE_NONE,
+ sprintf('Adds the "%s" role to the new API key.', Role::AUTHORED_SHORT_URLS),
+ )
+ ->addOption(
+ $domainOnly,
+ 'd',
+ InputOption::VALUE_REQUIRED,
+ sprintf('Adds the "%s" role to the new API key, with the domain provided.', Role::DOMAIN_SPECIFIC),
+ )
+ ->setHelp($help);
}
protected function execute(InputInterface $input, OutputInterface $output): ?int
{
$expirationDate = $input->getOption('expirationDate');
- $apiKey = $this->apiKeyService->create(isset($expirationDate) ? Chronos::parse($expirationDate) : null);
+ $apiKey = $this->apiKeyService->create(
+ isset($expirationDate) ? Chronos::parse($expirationDate) : null,
+ ...$this->roleResolver->determineRoles($input),
+ );
+
+ $io = new SymfonyStyle($input, $output);
+ $io->success(sprintf('Generated API key: "%s"', $apiKey->toString()));
+
+ if (! $apiKey->isAdmin()) {
+ ShlinkTable::fromOutput($io)->render(
+ ['Role name', 'Role metadata'],
+ $apiKey->mapRoles(fn (string $name, array $meta) => [$name, arrayToString($meta, 0)]),
+ null,
+ 'Roles',
+ );
+ }
- (new SymfonyStyle($input, $output))->success(sprintf('Generated API key: "%s"', $apiKey));
return ExitCodes::EXIT_SUCCESS;
}
}
diff --git a/module/CLI/src/Command/Api/ListKeysCommand.php b/module/CLI/src/Command/Api/ListKeysCommand.php
index f54ad8dd..cf09e614 100644
--- a/module/CLI/src/Command/Api/ListKeysCommand.php
+++ b/module/CLI/src/Command/Api/ListKeysCommand.php
@@ -6,6 +6,7 @@ namespace Shlinkio\Shlink\CLI\Command\Api;
use Shlinkio\Shlink\CLI\Util\ExitCodes;
use Shlinkio\Shlink\CLI\Util\ShlinkTable;
+use Shlinkio\Shlink\Rest\ApiKey\Role;
use Shlinkio\Shlink\Rest\Entity\ApiKey;
use Shlinkio\Shlink\Rest\Service\ApiKeyServiceInterface;
use Symfony\Component\Console\Command\Command;
@@ -14,7 +15,8 @@ use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use function array_filter;
-use function array_map;
+use function Functional\map;
+use function implode;
use function sprintf;
class ListKeysCommand extends Command
@@ -50,7 +52,7 @@ class ListKeysCommand extends Command
{
$enabledOnly = $input->getOption('enabledOnly');
- $rows = array_map(function (ApiKey $apiKey) use ($enabledOnly) {
+ $rows = map($this->apiKeyService->listKeys($enabledOnly), function (ApiKey $apiKey) use ($enabledOnly) {
$expiration = $apiKey->getExpirationDate();
$messagePattern = $this->determineMessagePattern($apiKey);
@@ -60,13 +62,21 @@ class ListKeysCommand extends Command
$rowData[] = sprintf($messagePattern, $this->getEnabledSymbol($apiKey));
}
$rowData[] = $expiration !== null ? $expiration->toAtomString() : '-';
+ $rowData[] = $apiKey->isAdmin() ? 'Admin' : implode("\n", $apiKey->mapRoles(
+ fn (string $roleName, array $meta) =>
+ empty($meta)
+ ? Role::toFriendlyName($roleName)
+ : sprintf('%s: %s', Role::toFriendlyName($roleName), Role::domainAuthorityFromMeta($meta)),
+ ));
+
return $rowData;
- }, $this->apiKeyService->listKeys($enabledOnly));
+ });
ShlinkTable::fromOutput($output)->render(array_filter([
'Key',
! $enabledOnly ? 'Is enabled' : null,
'Expiration date',
+ 'Roles',
]), $rows);
return ExitCodes::EXIT_SUCCESS;
}
@@ -80,8 +90,6 @@ class ListKeysCommand extends Command
return $apiKey->isExpired() ? self::WARNING_STRING_PATTERN : self::SUCCESS_STRING_PATTERN;
}
- /**
- */
private function getEnabledSymbol(ApiKey $apiKey): string
{
return ! $apiKey->isEnabled() || $apiKey->isExpired() ? '---' : '+++';
diff --git a/module/CLI/src/Command/Domain/ListDomainsCommand.php b/module/CLI/src/Command/Domain/ListDomainsCommand.php
index 0368f1dd..ddcfa1bd 100644
--- a/module/CLI/src/Command/Domain/ListDomainsCommand.php
+++ b/module/CLI/src/Command/Domain/ListDomainsCommand.php
@@ -7,7 +7,7 @@ namespace Shlinkio\Shlink\CLI\Command\Domain;
use Shlinkio\Shlink\CLI\Util\ExitCodes;
use Shlinkio\Shlink\CLI\Util\ShlinkTable;
use Shlinkio\Shlink\Core\Domain\DomainServiceInterface;
-use Shlinkio\Shlink\Core\Entity\Domain;
+use Shlinkio\Shlink\Core\Domain\Model\DomainItem;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
@@ -19,13 +19,11 @@ class ListDomainsCommand extends Command
public const NAME = 'domain:list';
private DomainServiceInterface $domainService;
- private string $defaultDomain;
- public function __construct(DomainServiceInterface $domainService, string $defaultDomain)
+ public function __construct(DomainServiceInterface $domainService)
{
parent::__construct();
$this->domainService = $domainService;
- $this->defaultDomain = $defaultDomain;
}
protected function configure(): void
@@ -37,12 +35,12 @@ class ListDomainsCommand extends Command
protected function execute(InputInterface $input, OutputInterface $output): ?int
{
- $regularDomains = $this->domainService->listDomainsWithout($this->defaultDomain);
+ $domains = $this->domainService->listDomains();
- ShlinkTable::fromOutput($output)->render(['Domain', 'Is default'], [
- [$this->defaultDomain, 'Yes'],
- ...map($regularDomains, fn (Domain $domain) => [$domain->getAuthority(), 'No']),
- ]);
+ ShlinkTable::fromOutput($output)->render(
+ ['Domain', 'Is default'],
+ map($domains, fn (DomainItem $domain) => [$domain->toString(), $domain->isDefault() ? 'Yes' : 'No']),
+ );
return ExitCodes::EXIT_SUCCESS;
}
diff --git a/module/CLI/src/Command/Tag/RenameTagCommand.php b/module/CLI/src/Command/Tag/RenameTagCommand.php
index fe42a832..8bfb0242 100644
--- a/module/CLI/src/Command/Tag/RenameTagCommand.php
+++ b/module/CLI/src/Command/Tag/RenameTagCommand.php
@@ -7,6 +7,7 @@ namespace Shlinkio\Shlink\CLI\Command\Tag;
use Shlinkio\Shlink\CLI\Util\ExitCodes;
use Shlinkio\Shlink\Core\Exception\TagConflictException;
use Shlinkio\Shlink\Core\Exception\TagNotFoundException;
+use Shlinkio\Shlink\Core\Tag\Model\TagRenaming;
use Shlinkio\Shlink\Core\Tag\TagServiceInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
@@ -42,7 +43,7 @@ class RenameTagCommand extends Command
$newName = $input->getArgument('newName');
try {
- $this->tagService->renameTag($oldName, $newName);
+ $this->tagService->renameTag(TagRenaming::fromNames($oldName, $newName));
$io->success('Tag properly renamed.');
return ExitCodes::EXIT_SUCCESS;
} catch (TagNotFoundException | TagConflictException $e) {
diff --git a/module/CLI/test/ApiKey/RoleResolverTest.php b/module/CLI/test/ApiKey/RoleResolverTest.php
new file mode 100644
index 00000000..a50c2b12
--- /dev/null
+++ b/module/CLI/test/ApiKey/RoleResolverTest.php
@@ -0,0 +1,82 @@
+domainService = $this->prophesize(DomainServiceInterface::class);
+ $this->resolver = new RoleResolver($this->domainService->reveal());
+ }
+
+ /**
+ * @test
+ * @dataProvider provideRoles
+ */
+ public function properRolesAreResolvedBasedOnInput(
+ InputInterface $input,
+ array $expectedRoles,
+ int $expectedDomainCalls
+ ): void {
+ $getDomain = $this->domainService->getOrCreate('example.com')->willReturn(
+ (new Domain('example.com'))->setId('1'),
+ );
+
+ $result = $this->resolver->determineRoles($input);
+
+ self::assertEquals($expectedRoles, $result);
+ $getDomain->shouldHaveBeenCalledTimes($expectedDomainCalls);
+ }
+
+ public function provideRoles(): iterable
+ {
+ $domain = (new Domain('example.com'))->setId('1');
+ $buildInput = function (array $definition): InputInterface {
+ $input = $this->prophesize(InputInterface::class);
+
+ foreach ($definition as $name => $value) {
+ $input->getOption($name)->willReturn($value);
+ }
+
+ return $input->reveal();
+ };
+
+ yield 'no roles' => [
+ $buildInput([RoleResolver::DOMAIN_ONLY_PARAM => null, RoleResolver::AUTHOR_ONLY_PARAM => false]),
+ [],
+ 0,
+ ];
+ yield 'domain role only' => [
+ $buildInput([RoleResolver::DOMAIN_ONLY_PARAM => 'example.com', RoleResolver::AUTHOR_ONLY_PARAM => false]),
+ [RoleDefinition::forDomain($domain)],
+ 1,
+ ];
+ yield 'author role only' => [
+ $buildInput([RoleResolver::DOMAIN_ONLY_PARAM => null, RoleResolver::AUTHOR_ONLY_PARAM => true]),
+ [RoleDefinition::forAuthoredShortUrls()],
+ 0,
+ ];
+ yield 'both roles' => [
+ $buildInput([RoleResolver::DOMAIN_ONLY_PARAM => 'example.com', RoleResolver::AUTHOR_ONLY_PARAM => true]),
+ [RoleDefinition::forAuthoredShortUrls(), RoleDefinition::forDomain($domain)],
+ 1,
+ ];
+ }
+}
diff --git a/module/CLI/test/Command/Api/GenerateKeyCommandTest.php b/module/CLI/test/Command/Api/GenerateKeyCommandTest.php
index 7ff87a3f..744fb482 100644
--- a/module/CLI/test/Command/Api/GenerateKeyCommandTest.php
+++ b/module/CLI/test/Command/Api/GenerateKeyCommandTest.php
@@ -9,10 +9,12 @@ use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;
use Prophecy\Prophecy\ObjectProphecy;
+use Shlinkio\Shlink\CLI\ApiKey\RoleResolverInterface;
use Shlinkio\Shlink\CLI\Command\Api\GenerateKeyCommand;
use Shlinkio\Shlink\Rest\Entity\ApiKey;
use Shlinkio\Shlink\Rest\Service\ApiKeyServiceInterface;
use Symfony\Component\Console\Application;
+use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Tester\CommandTester;
class GenerateKeyCommandTest extends TestCase
@@ -21,11 +23,15 @@ class GenerateKeyCommandTest extends TestCase
private CommandTester $commandTester;
private ObjectProphecy $apiKeyService;
+ private ObjectProphecy $roleResolver;
public function setUp(): void
{
$this->apiKeyService = $this->prophesize(ApiKeyServiceInterface::class);
- $command = new GenerateKeyCommand($this->apiKeyService->reveal());
+ $this->roleResolver = $this->prophesize(RoleResolverInterface::class);
+ $this->roleResolver->determineRoles(Argument::type(InputInterface::class))->willReturn([]);
+
+ $command = new GenerateKeyCommand($this->apiKeyService->reveal(), $this->roleResolver->reveal());
$app = new Application();
$app->add($command);
$this->commandTester = new CommandTester($command);
diff --git a/module/CLI/test/Command/Api/ListKeysCommandTest.php b/module/CLI/test/Command/Api/ListKeysCommandTest.php
index ccf3b0ee..116f979d 100644
--- a/module/CLI/test/Command/Api/ListKeysCommandTest.php
+++ b/module/CLI/test/Command/Api/ListKeysCommandTest.php
@@ -8,6 +8,8 @@ use PHPUnit\Framework\TestCase;
use Prophecy\PhpUnit\ProphecyTrait;
use Prophecy\Prophecy\ObjectProphecy;
use Shlinkio\Shlink\CLI\Command\Api\ListKeysCommand;
+use Shlinkio\Shlink\Core\Entity\Domain;
+use Shlinkio\Shlink\Rest\ApiKey\Model\RoleDefinition;
use Shlinkio\Shlink\Rest\Entity\ApiKey;
use Shlinkio\Shlink\Rest\Service\ApiKeyServiceInterface;
use Symfony\Component\Console\Application;
@@ -29,42 +31,87 @@ class ListKeysCommandTest extends TestCase
$this->commandTester = new CommandTester($command);
}
- /** @test */
- public function everythingIsListedIfEnabledOnlyIsNotProvided(): void
+ /**
+ * @test
+ * @dataProvider provideKeysAndOutputs
+ */
+ public function returnsExpectedOutput(array $keys, bool $enabledOnly, string $expected): void
{
- $this->apiKeyService->listKeys(false)->willReturn([
- new ApiKey(),
- new ApiKey(),
- new ApiKey(),
- ])->shouldBeCalledOnce();
+ $listKeys = $this->apiKeyService->listKeys($enabledOnly)->willReturn($keys);
- $this->commandTester->execute([]);
+ $this->commandTester->execute(['--enabledOnly' => $enabledOnly]);
$output = $this->commandTester->getDisplay();
- self::assertStringContainsString('Key', $output);
- self::assertStringContainsString('Is enabled', $output);
- self::assertStringContainsString(' +++ ', $output);
- self::assertStringNotContainsString(' --- ', $output);
- self::assertStringContainsString('Expiration date', $output);
+ self::assertEquals($expected, $output);
+ $listKeys->shouldHaveBeenCalledOnce();
}
- /** @test */
- public function onlyEnabledKeysAreListedIfEnabledOnlyIsProvided(): void
+ public function provideKeysAndOutputs(): iterable
{
- $this->apiKeyService->listKeys(true)->willReturn([
- (new ApiKey())->disable(),
- new ApiKey(),
- ])->shouldBeCalledOnce();
+ yield 'all keys' => [
+ [ApiKey::withKey('foo'), ApiKey::withKey('bar'), ApiKey::withKey('baz')],
+ false,
+ <<
- *
- * The return value is cast to an integer.
- * @since 5.1.0
- */
public function count(): int
{
return $this->repository->countList(
$this->params->searchTerm(),
$this->params->tags(),
$this->params->dateRange(),
+ $this->resolveSpec(),
);
}
+
+ private function resolveSpec(): ?Specification
+ {
+ return $this->apiKey !== null ? $this->apiKey->spec() : null;
+ }
}
diff --git a/module/Core/src/Paginator/Adapter/VisitsForTagPaginatorAdapter.php b/module/Core/src/Paginator/Adapter/VisitsForTagPaginatorAdapter.php
index e80fbcdd..3b73509a 100644
--- a/module/Core/src/Paginator/Adapter/VisitsForTagPaginatorAdapter.php
+++ b/module/Core/src/Paginator/Adapter/VisitsForTagPaginatorAdapter.php
@@ -4,20 +4,28 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Core\Paginator\Adapter;
+use Happyr\DoctrineSpecification\Specification\Specification;
use Shlinkio\Shlink\Core\Model\VisitsParams;
use Shlinkio\Shlink\Core\Repository\VisitRepositoryInterface;
+use Shlinkio\Shlink\Rest\Entity\ApiKey;
class VisitsForTagPaginatorAdapter extends AbstractCacheableCountPaginatorAdapter
{
private VisitRepositoryInterface $visitRepository;
private string $tag;
private VisitsParams $params;
+ private ?ApiKey $apiKey;
- public function __construct(VisitRepositoryInterface $visitRepository, string $tag, VisitsParams $params)
- {
+ public function __construct(
+ VisitRepositoryInterface $visitRepository,
+ string $tag,
+ VisitsParams $params,
+ ?ApiKey $apiKey
+ ) {
$this->visitRepository = $visitRepository;
$this->params = $params;
$this->tag = $tag;
+ $this->apiKey = $apiKey;
}
public function getItems($offset, $itemCountPerPage): array // phpcs:ignore
@@ -27,11 +35,21 @@ class VisitsForTagPaginatorAdapter extends AbstractCacheableCountPaginatorAdapte
$this->params->getDateRange(),
$itemCountPerPage,
$offset,
+ $this->resolveSpec(),
);
}
protected function doCount(): int
{
- return $this->visitRepository->countVisitsByTag($this->tag, $this->params->getDateRange());
+ return $this->visitRepository->countVisitsByTag(
+ $this->tag,
+ $this->params->getDateRange(),
+ $this->resolveSpec(),
+ );
+ }
+
+ private function resolveSpec(): ?Specification
+ {
+ return $this->apiKey !== null ? $this->apiKey->spec(true) : null;
}
}
diff --git a/module/Core/src/Paginator/Adapter/VisitsPaginatorAdapter.php b/module/Core/src/Paginator/Adapter/VisitsPaginatorAdapter.php
index 404ae309..29498a6d 100644
--- a/module/Core/src/Paginator/Adapter/VisitsPaginatorAdapter.php
+++ b/module/Core/src/Paginator/Adapter/VisitsPaginatorAdapter.php
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Core\Paginator\Adapter;
+use Happyr\DoctrineSpecification\Specification\Specification;
use Shlinkio\Shlink\Core\Model\ShortUrlIdentifier;
use Shlinkio\Shlink\Core\Model\VisitsParams;
use Shlinkio\Shlink\Core\Repository\VisitRepositoryInterface;
@@ -13,15 +14,18 @@ class VisitsPaginatorAdapter extends AbstractCacheableCountPaginatorAdapter
private VisitRepositoryInterface $visitRepository;
private ShortUrlIdentifier $identifier;
private VisitsParams $params;
+ private ?Specification $spec;
public function __construct(
VisitRepositoryInterface $visitRepository,
ShortUrlIdentifier $identifier,
- VisitsParams $params
+ VisitsParams $params,
+ ?Specification $spec
) {
$this->visitRepository = $visitRepository;
$this->params = $params;
$this->identifier = $identifier;
+ $this->spec = $spec;
}
public function getItems($offset, $itemCountPerPage): array // phpcs:ignore
@@ -32,6 +36,7 @@ class VisitsPaginatorAdapter extends AbstractCacheableCountPaginatorAdapter
$this->params->getDateRange(),
$itemCountPerPage,
$offset,
+ $this->spec,
);
}
@@ -41,6 +46,7 @@ class VisitsPaginatorAdapter extends AbstractCacheableCountPaginatorAdapter
$this->identifier->shortCode(),
$this->identifier->domain(),
$this->params->getDateRange(),
+ $this->spec,
);
}
}
diff --git a/module/Core/src/Repository/ShortUrlRepository.php b/module/Core/src/Repository/ShortUrlRepository.php
index 27dac54b..ddfaa189 100644
--- a/module/Core/src/Repository/ShortUrlRepository.php
+++ b/module/Core/src/Repository/ShortUrlRepository.php
@@ -4,9 +4,11 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Core\Repository;
-use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;
+use Happyr\DoctrineSpecification\EntitySpecificationRepository;
+use Happyr\DoctrineSpecification\Specification\Specification;
+use Shlinkio\Shlink\Common\Doctrine\Type\ChronosDateTimeType;
use Shlinkio\Shlink\Common\Util\DateRange;
use Shlinkio\Shlink\Core\Entity\ShortUrl;
use Shlinkio\Shlink\Core\Model\ShortUrlMeta;
@@ -18,7 +20,7 @@ use function array_key_exists;
use function count;
use function Functional\contains;
-class ShortUrlRepository extends EntityRepository implements ShortUrlRepositoryInterface
+class ShortUrlRepository extends EntitySpecificationRepository implements ShortUrlRepositoryInterface
{
/**
* @param string[] $tags
@@ -30,18 +32,13 @@ class ShortUrlRepository extends EntityRepository implements ShortUrlRepositoryI
?string $searchTerm = null,
array $tags = [],
?ShortUrlsOrdering $orderBy = null,
- ?DateRange $dateRange = null
+ ?DateRange $dateRange = null,
+ ?Specification $spec = null
): array {
- $qb = $this->createListQueryBuilder($searchTerm, $tags, $dateRange);
- $qb->select('DISTINCT s');
-
- // Set limit and offset
- if ($limit !== null) {
- $qb->setMaxResults($limit);
- }
- if ($offset !== null) {
- $qb->setFirstResult($offset);
- }
+ $qb = $this->createListQueryBuilder($searchTerm, $tags, $dateRange, $spec);
+ $qb->select('DISTINCT s')
+ ->setMaxResults($limit)
+ ->setFirstResult($offset);
// In case the ordering has been specified, the query could be more complex. Process it
if ($orderBy !== null && $orderBy->hasOrderField()) {
@@ -80,18 +77,23 @@ class ShortUrlRepository extends EntityRepository implements ShortUrlRepositoryI
return $qb->getQuery()->getResult();
}
- public function countList(?string $searchTerm = null, array $tags = [], ?DateRange $dateRange = null): int
- {
- $qb = $this->createListQueryBuilder($searchTerm, $tags, $dateRange);
+ public function countList(
+ ?string $searchTerm = null,
+ array $tags = [],
+ ?DateRange $dateRange = null,
+ ?Specification $spec = null
+ ): int {
+ $qb = $this->createListQueryBuilder($searchTerm, $tags, $dateRange, $spec);
$qb->select('COUNT(DISTINCT s)');
return (int) $qb->getQuery()->getSingleScalarResult();
}
private function createListQueryBuilder(
- ?string $searchTerm = null,
- array $tags = [],
- ?DateRange $dateRange = null
+ ?string $searchTerm,
+ array $tags,
+ ?DateRange $dateRange,
+ ?Specification $spec
): QueryBuilder {
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->from(ShortUrl::class, 's')
@@ -99,11 +101,11 @@ class ShortUrlRepository extends EntityRepository implements ShortUrlRepositoryI
if ($dateRange !== null && $dateRange->getStartDate() !== null) {
$qb->andWhere($qb->expr()->gte('s.dateCreated', ':startDate'));
- $qb->setParameter('startDate', $dateRange->getStartDate());
+ $qb->setParameter('startDate', $dateRange->getStartDate(), ChronosDateTimeType::CHRONOS_DATETIME);
}
if ($dateRange !== null && $dateRange->getEndDate() !== null) {
$qb->andWhere($qb->expr()->lte('s.dateCreated', ':endDate'));
- $qb->setParameter('endDate', $dateRange->getEndDate());
+ $qb->setParameter('endDate', $dateRange->getEndDate(), ChronosDateTimeType::CHRONOS_DATETIME);
}
// Apply search term to every searchable field if not empty
@@ -130,6 +132,8 @@ class ShortUrlRepository extends EntityRepository implements ShortUrlRepositoryI
->andWhere($qb->expr()->in('t.name', $tags));
}
+ $this->applySpecification($qb, $spec, 's');
+
return $qb;
}
@@ -147,7 +151,7 @@ class ShortUrlRepository extends EntityRepository implements ShortUrlRepositoryI
WHERE s.shortCode = :shortCode
AND (s.domain IS NULL OR d.authority = :domain)
ORDER BY s.domain {$ordering}
-DQL;
+ DQL;
$query = $this->getEntityManager()->createQuery($dql);
$query->setMaxResults(1)
@@ -165,23 +169,23 @@ DQL;
return $query->getOneOrNullResult();
}
- public function findOne(string $shortCode, ?string $domain = null): ?ShortUrl
+ public function findOne(string $shortCode, ?string $domain = null, ?Specification $spec = null): ?ShortUrl
{
- $qb = $this->createFindOneQueryBuilder($shortCode, $domain);
+ $qb = $this->createFindOneQueryBuilder($shortCode, $domain, $spec);
$qb->select('s');
return $qb->getQuery()->getOneOrNullResult();
}
- public function shortCodeIsInUse(string $slug, ?string $domain = null): bool
+ public function shortCodeIsInUse(string $slug, ?string $domain = null, ?Specification $spec = null): bool
{
- $qb = $this->createFindOneQueryBuilder($slug, $domain);
+ $qb = $this->createFindOneQueryBuilder($slug, $domain, $spec);
$qb->select('COUNT(DISTINCT s.id)');
return ((int) $qb->getQuery()->getSingleScalarResult()) > 0;
}
- private function createFindOneQueryBuilder(string $slug, ?string $domain = null): QueryBuilder
+ private function createFindOneQueryBuilder(string $slug, ?string $domain, ?Specification $spec): QueryBuilder
{
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->from(ShortUrl::class, 's')
@@ -192,6 +196,8 @@ DQL;
$this->whereDomainIs($qb, $domain);
+ $this->applySpecification($qb, $spec, 's');
+
return $qb;
}
@@ -216,19 +222,23 @@ DQL;
}
if ($meta->hasValidSince()) {
$qb->andWhere($qb->expr()->eq('s.validSince', ':validSince'))
- ->setParameter('validSince', $meta->getValidSince());
+ ->setParameter('validSince', $meta->getValidSince(), ChronosDateTimeType::CHRONOS_DATETIME);
}
if ($meta->hasValidUntil()) {
$qb->andWhere($qb->expr()->eq('s.validUntil', ':validUntil'))
- ->setParameter('validUntil', $meta->getValidUntil());
+ ->setParameter('validUntil', $meta->getValidUntil(), ChronosDateTimeType::CHRONOS_DATETIME);
}
-
if ($meta->hasDomain()) {
$qb->join('s.domain', 'd')
->andWhere($qb->expr()->eq('d.authority', ':domain'))
->setParameter('domain', $meta->getDomain());
}
+ $apiKey = $meta->getApiKey();
+ if ($apiKey !== null) {
+ $this->applySpecification($qb, $apiKey->spec(), 's');
+ }
+
$tagsAmount = count($tags);
if ($tagsAmount === 0) {
return $qb->getQuery()->getOneOrNullResult();
diff --git a/module/Core/src/Repository/ShortUrlRepositoryInterface.php b/module/Core/src/Repository/ShortUrlRepositoryInterface.php
index 1d6f38a8..a0131f6f 100644
--- a/module/Core/src/Repository/ShortUrlRepositoryInterface.php
+++ b/module/Core/src/Repository/ShortUrlRepositoryInterface.php
@@ -5,13 +5,15 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Core\Repository;
use Doctrine\Persistence\ObjectRepository;
+use Happyr\DoctrineSpecification\EntitySpecificationRepositoryInterface;
+use Happyr\DoctrineSpecification\Specification\Specification;
use Shlinkio\Shlink\Common\Util\DateRange;
use Shlinkio\Shlink\Core\Entity\ShortUrl;
use Shlinkio\Shlink\Core\Model\ShortUrlMeta;
use Shlinkio\Shlink\Core\Model\ShortUrlsOrdering;
use Shlinkio\Shlink\Importer\Model\ImportedShlinkUrl;
-interface ShortUrlRepositoryInterface extends ObjectRepository
+interface ShortUrlRepositoryInterface extends ObjectRepository, EntitySpecificationRepositoryInterface
{
public function findList(
?int $limit = null,
@@ -19,16 +21,22 @@ interface ShortUrlRepositoryInterface extends ObjectRepository
?string $searchTerm = null,
array $tags = [],
?ShortUrlsOrdering $orderBy = null,
- ?DateRange $dateRange = null
+ ?DateRange $dateRange = null,
+ ?Specification $spec = null
): array;
- public function countList(?string $searchTerm = null, array $tags = [], ?DateRange $dateRange = null): int;
+ public function countList(
+ ?string $searchTerm = null,
+ array $tags = [],
+ ?DateRange $dateRange = null,
+ ?Specification $spec = null
+ ): int;
public function findOneWithDomainFallback(string $shortCode, ?string $domain = null): ?ShortUrl;
- public function findOne(string $shortCode, ?string $domain = null): ?ShortUrl;
+ public function findOne(string $shortCode, ?string $domain = null, ?Specification $spec = null): ?ShortUrl;
- public function shortCodeIsInUse(string $slug, ?string $domain): bool;
+ public function shortCodeIsInUse(string $slug, ?string $domain, ?Specification $spec = null): bool;
public function findOneMatching(string $url, array $tags, ShortUrlMeta $meta): ?ShortUrl;
diff --git a/module/Core/src/Repository/TagRepository.php b/module/Core/src/Repository/TagRepository.php
index 05b2481c..dd15c292 100644
--- a/module/Core/src/Repository/TagRepository.php
+++ b/module/Core/src/Repository/TagRepository.php
@@ -4,13 +4,18 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Core\Repository;
-use Doctrine\ORM\EntityRepository;
+use Happyr\DoctrineSpecification\EntitySpecificationRepository;
+use Happyr\DoctrineSpecification\Spec;
+use Happyr\DoctrineSpecification\Specification\Specification;
use Shlinkio\Shlink\Core\Entity\Tag;
use Shlinkio\Shlink\Core\Tag\Model\TagInfo;
+use Shlinkio\Shlink\Core\Tag\Spec\CountTagsWithName;
+use Shlinkio\Shlink\Rest\ApiKey\Spec\WithApiKeySpecsEnsuringJoin;
+use Shlinkio\Shlink\Rest\Entity\ApiKey;
use function Functional\map;
-class TagRepository extends EntityRepository implements TagRepositoryInterface
+class TagRepository extends EntitySpecificationRepository implements TagRepositoryInterface
{
public function deleteByName(array $names): int
{
@@ -28,21 +33,32 @@ class TagRepository extends EntityRepository implements TagRepositoryInterface
/**
* @return TagInfo[]
*/
- public function findTagsWithInfo(): array
+ public function findTagsWithInfo(?Specification $spec = null): array
{
- $dql = <<getEntityManager()->createQuery($dql);
+ $qb = $this->createQueryBuilder('t');
+ $qb->select('t AS tag', 'COUNT(DISTINCT s.id) AS shortUrlsCount', 'COUNT(DISTINCT v.id) AS visitsCount')
+ ->leftJoin('t.shortUrls', 's')
+ ->leftJoin('s.visits', 'v')
+ ->groupBy('t')
+ ->orderBy('t.name', 'ASC');
+
+ $this->applySpecification($qb, $spec, 't');
+
+ $query = $qb->getQuery();
return map(
$query->getResult(),
fn (array $row) => new TagInfo($row['tag'], (int) $row['shortUrlsCount'], (int) $row['visitsCount']),
);
}
+
+ public function tagExists(string $tag, ?ApiKey $apiKey = null): bool
+ {
+ $result = (int) $this->matchSingleScalarResult(Spec::andX(
+ new CountTagsWithName($tag),
+ new WithApiKeySpecsEnsuringJoin($apiKey),
+ ));
+
+ return $result > 0;
+ }
}
diff --git a/module/Core/src/Repository/TagRepositoryInterface.php b/module/Core/src/Repository/TagRepositoryInterface.php
index 37179e21..86898ed1 100644
--- a/module/Core/src/Repository/TagRepositoryInterface.php
+++ b/module/Core/src/Repository/TagRepositoryInterface.php
@@ -5,14 +5,19 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Core\Repository;
use Doctrine\Persistence\ObjectRepository;
+use Happyr\DoctrineSpecification\EntitySpecificationRepositoryInterface;
+use Happyr\DoctrineSpecification\Specification\Specification;
use Shlinkio\Shlink\Core\Tag\Model\TagInfo;
+use Shlinkio\Shlink\Rest\Entity\ApiKey;
-interface TagRepositoryInterface extends ObjectRepository
+interface TagRepositoryInterface extends ObjectRepository, EntitySpecificationRepositoryInterface
{
public function deleteByName(array $names): int;
/**
* @return TagInfo[]
*/
- public function findTagsWithInfo(): array;
+ public function findTagsWithInfo(?Specification $spec = null): array;
+
+ public function tagExists(string $tag, ?ApiKey $apiKey = null): bool;
}
diff --git a/module/Core/src/Repository/VisitRepository.php b/module/Core/src/Repository/VisitRepository.php
index 458b8ef2..a1df73a5 100644
--- a/module/Core/src/Repository/VisitRepository.php
+++ b/module/Core/src/Repository/VisitRepository.php
@@ -4,17 +4,21 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Core\Repository;
-use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\ResultSetMappingBuilder;
use Doctrine\ORM\QueryBuilder;
+use Happyr\DoctrineSpecification\EntitySpecificationRepository;
+use Happyr\DoctrineSpecification\Spec;
+use Happyr\DoctrineSpecification\Specification\Specification;
use Shlinkio\Shlink\Common\Util\DateRange;
use Shlinkio\Shlink\Core\Entity\ShortUrl;
use Shlinkio\Shlink\Core\Entity\Visit;
use Shlinkio\Shlink\Core\Entity\VisitLocation;
+use Shlinkio\Shlink\Rest\ApiKey\Spec\WithApiKeySpecsEnsuringJoin;
+use Shlinkio\Shlink\Rest\Entity\ApiKey;
use const PHP_INT_MAX;
-class VisitRepository extends EntityRepository implements VisitRepositoryInterface
+class VisitRepository extends EntitySpecificationRepository implements VisitRepositoryInterface
{
/**
* @return iterable|Visit[]
@@ -84,15 +88,20 @@ class VisitRepository extends EntityRepository implements VisitRepositoryInterfa
?string $domain = null,
?DateRange $dateRange = null,
?int $limit = null,
- ?int $offset = null
+ ?int $offset = null,
+ ?Specification $spec = null
): array {
- $qb = $this->createVisitsByShortCodeQueryBuilder($shortCode, $domain, $dateRange);
+ $qb = $this->createVisitsByShortCodeQueryBuilder($shortCode, $domain, $dateRange, $spec);
return $this->resolveVisitsWithNativeQuery($qb, $limit, $offset);
}
- public function countVisitsByShortCode(string $shortCode, ?string $domain = null, ?DateRange $dateRange = null): int
- {
- $qb = $this->createVisitsByShortCodeQueryBuilder($shortCode, $domain, $dateRange);
+ public function countVisitsByShortCode(
+ string $shortCode,
+ ?string $domain = null,
+ ?DateRange $dateRange = null,
+ ?Specification $spec = null
+ ): int {
+ $qb = $this->createVisitsByShortCodeQueryBuilder($shortCode, $domain, $dateRange, $spec);
$qb->select('COUNT(v.id)');
return (int) $qb->getQuery()->getSingleScalarResult();
@@ -101,11 +110,12 @@ class VisitRepository extends EntityRepository implements VisitRepositoryInterfa
private function createVisitsByShortCodeQueryBuilder(
string $shortCode,
?string $domain,
- ?DateRange $dateRange
+ ?DateRange $dateRange,
+ ?Specification $spec = null
): QueryBuilder {
/** @var ShortUrlRepositoryInterface $shortUrlRepo */
$shortUrlRepo = $this->getEntityManager()->getRepository(ShortUrl::class);
- $shortUrl = $shortUrlRepo->findOne($shortCode, $domain);
+ $shortUrl = $shortUrlRepo->findOne($shortCode, $domain, $spec);
$shortUrlId = $shortUrl !== null ? $shortUrl->getId() : -1;
// Parameters in this query need to be part of the query itself, as we need to use it a sub-query later
@@ -124,32 +134,36 @@ class VisitRepository extends EntityRepository implements VisitRepositoryInterfa
string $tag,
?DateRange $dateRange = null,
?int $limit = null,
- ?int $offset = null
+ ?int $offset = null,
+ ?Specification $spec = null
): array {
- $qb = $this->createVisitsByTagQueryBuilder($tag, $dateRange);
+ $qb = $this->createVisitsByTagQueryBuilder($tag, $dateRange, $spec);
return $this->resolveVisitsWithNativeQuery($qb, $limit, $offset);
}
- public function countVisitsByTag(string $tag, ?DateRange $dateRange = null): int
+ public function countVisitsByTag(string $tag, ?DateRange $dateRange = null, ?Specification $spec = null): int
{
- $qb = $this->createVisitsByTagQueryBuilder($tag, $dateRange);
+ $qb = $this->createVisitsByTagQueryBuilder($tag, $dateRange, $spec);
$qb->select('COUNT(v.id)');
return (int) $qb->getQuery()->getSingleScalarResult();
}
- private function createVisitsByTagQueryBuilder(string $tag, ?DateRange $dateRange = null): QueryBuilder
- {
- // Parameters in this query need to be part of the query itself, as we need to use it a sub-query later
+ private function createVisitsByTagQueryBuilder(
+ string $tag,
+ ?DateRange $dateRange,
+ ?Specification $spec
+ ): QueryBuilder {
+ // Parameters in this query need to be inlined, not bound, as we need to use it as sub-query later
// Since they are not strictly provided by the caller, it's reasonably safe
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->from(Visit::class, 'v')
->join('v.shortUrl', 's')
->join('s.tags', 't')
- ->where($qb->expr()->eq('t.name', '\'' . $tag . '\''));
+ ->where($qb->expr()->eq('t.name', '\'' . $tag . '\'')); // This needs to be concatenated, not bound
- // Apply date range filtering
$this->applyDatesInline($qb, $dateRange);
+ $this->applySpecification($qb, $spec, 'v');
return $qb;
}
@@ -194,4 +208,11 @@ class VisitRepository extends EntityRepository implements VisitRepositoryInterfa
return $query->getResult();
}
+
+ public function countVisits(?ApiKey $apiKey = null): int
+ {
+ return (int) $this->matchSingleScalarResult(
+ Spec::countOf(new WithApiKeySpecsEnsuringJoin($apiKey, 'shortUrl')),
+ );
+ }
}
diff --git a/module/Core/src/Repository/VisitRepositoryInterface.php b/module/Core/src/Repository/VisitRepositoryInterface.php
index 5a540171..526645df 100644
--- a/module/Core/src/Repository/VisitRepositoryInterface.php
+++ b/module/Core/src/Repository/VisitRepositoryInterface.php
@@ -5,10 +5,13 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Core\Repository;
use Doctrine\Persistence\ObjectRepository;
+use Happyr\DoctrineSpecification\EntitySpecificationRepositoryInterface;
+use Happyr\DoctrineSpecification\Specification\Specification;
use Shlinkio\Shlink\Common\Util\DateRange;
use Shlinkio\Shlink\Core\Entity\Visit;
+use Shlinkio\Shlink\Rest\Entity\ApiKey;
-interface VisitRepositoryInterface extends ObjectRepository
+interface VisitRepositoryInterface extends ObjectRepository, EntitySpecificationRepositoryInterface
{
public const DEFAULT_BLOCK_SIZE = 10000;
@@ -35,13 +38,15 @@ interface VisitRepositoryInterface extends ObjectRepository
?string $domain = null,
?DateRange $dateRange = null,
?int $limit = null,
- ?int $offset = null
+ ?int $offset = null,
+ ?Specification $spec = null
): array;
public function countVisitsByShortCode(
string $shortCode,
?string $domain = null,
- ?DateRange $dateRange = null
+ ?DateRange $dateRange = null,
+ ?Specification $spec = null
): int;
/**
@@ -51,8 +56,11 @@ interface VisitRepositoryInterface extends ObjectRepository
string $tag,
?DateRange $dateRange = null,
?int $limit = null,
- ?int $offset = null
+ ?int $offset = null,
+ ?Specification $spec = null
): array;
- public function countVisitsByTag(string $tag, ?DateRange $dateRange = null): int;
+ public function countVisitsByTag(string $tag, ?DateRange $dateRange = null, ?Specification $spec = null): int;
+
+ public function countVisits(?ApiKey $apiKey = null): int;
}
diff --git a/module/Core/src/Service/ShortUrl/DeleteShortUrlService.php b/module/Core/src/Service/ShortUrl/DeleteShortUrlService.php
index 35a540da..07af448d 100644
--- a/module/Core/src/Service/ShortUrl/DeleteShortUrlService.php
+++ b/module/Core/src/Service/ShortUrl/DeleteShortUrlService.php
@@ -9,6 +9,7 @@ use Shlinkio\Shlink\Core\Entity\ShortUrl;
use Shlinkio\Shlink\Core\Exception;
use Shlinkio\Shlink\Core\Model\ShortUrlIdentifier;
use Shlinkio\Shlink\Core\Options\DeleteShortUrlsOptions;
+use Shlinkio\Shlink\Rest\Entity\ApiKey;
class DeleteShortUrlService implements DeleteShortUrlServiceInterface
{
@@ -30,9 +31,12 @@ class DeleteShortUrlService implements DeleteShortUrlServiceInterface
* @throws Exception\ShortUrlNotFoundException
* @throws Exception\DeleteShortUrlException
*/
- public function deleteByShortCode(ShortUrlIdentifier $identifier, bool $ignoreThreshold = false): void
- {
- $shortUrl = $this->urlResolver->resolveShortUrl($identifier);
+ public function deleteByShortCode(
+ ShortUrlIdentifier $identifier,
+ bool $ignoreThreshold = false,
+ ?ApiKey $apiKey = null
+ ): void {
+ $shortUrl = $this->urlResolver->resolveShortUrl($identifier, $apiKey);
if (! $ignoreThreshold && $this->isThresholdReached($shortUrl)) {
throw Exception\DeleteShortUrlException::fromVisitsThreshold(
$this->deleteShortUrlsOptions->getVisitsThreshold(),
diff --git a/module/Core/src/Service/ShortUrl/DeleteShortUrlServiceInterface.php b/module/Core/src/Service/ShortUrl/DeleteShortUrlServiceInterface.php
index 4759bf24..b1f01839 100644
--- a/module/Core/src/Service/ShortUrl/DeleteShortUrlServiceInterface.php
+++ b/module/Core/src/Service/ShortUrl/DeleteShortUrlServiceInterface.php
@@ -6,6 +6,7 @@ namespace Shlinkio\Shlink\Core\Service\ShortUrl;
use Shlinkio\Shlink\Core\Exception;
use Shlinkio\Shlink\Core\Model\ShortUrlIdentifier;
+use Shlinkio\Shlink\Rest\Entity\ApiKey;
interface DeleteShortUrlServiceInterface
{
@@ -13,5 +14,9 @@ interface DeleteShortUrlServiceInterface
* @throws Exception\ShortUrlNotFoundException
* @throws Exception\DeleteShortUrlException
*/
- public function deleteByShortCode(ShortUrlIdentifier $identifier, bool $ignoreThreshold = false): void;
+ public function deleteByShortCode(
+ ShortUrlIdentifier $identifier,
+ bool $ignoreThreshold = false,
+ ?ApiKey $apiKey = null
+ ): void;
}
diff --git a/module/Core/src/Service/ShortUrl/ShortUrlResolver.php b/module/Core/src/Service/ShortUrl/ShortUrlResolver.php
index 414a3446..6e03114c 100644
--- a/module/Core/src/Service/ShortUrl/ShortUrlResolver.php
+++ b/module/Core/src/Service/ShortUrl/ShortUrlResolver.php
@@ -9,6 +9,7 @@ use Shlinkio\Shlink\Core\Entity\ShortUrl;
use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException;
use Shlinkio\Shlink\Core\Model\ShortUrlIdentifier;
use Shlinkio\Shlink\Core\Repository\ShortUrlRepository;
+use Shlinkio\Shlink\Rest\Entity\ApiKey;
class ShortUrlResolver implements ShortUrlResolverInterface
{
@@ -22,11 +23,15 @@ class ShortUrlResolver implements ShortUrlResolverInterface
/**
* @throws ShortUrlNotFoundException
*/
- public function resolveShortUrl(ShortUrlIdentifier $identifier): ShortUrl
+ public function resolveShortUrl(ShortUrlIdentifier $identifier, ?ApiKey $apiKey = null): ShortUrl
{
/** @var ShortUrlRepository $shortUrlRepo */
$shortUrlRepo = $this->em->getRepository(ShortUrl::class);
- $shortUrl = $shortUrlRepo->findOne($identifier->shortCode(), $identifier->domain());
+ $shortUrl = $shortUrlRepo->findOne(
+ $identifier->shortCode(),
+ $identifier->domain(),
+ $apiKey !== null ? $apiKey->spec() : null,
+ );
if ($shortUrl === null) {
throw ShortUrlNotFoundException::fromNotFound($identifier);
}
diff --git a/module/Core/src/Service/ShortUrl/ShortUrlResolverInterface.php b/module/Core/src/Service/ShortUrl/ShortUrlResolverInterface.php
index a3a7c115..daa66e43 100644
--- a/module/Core/src/Service/ShortUrl/ShortUrlResolverInterface.php
+++ b/module/Core/src/Service/ShortUrl/ShortUrlResolverInterface.php
@@ -7,13 +7,14 @@ namespace Shlinkio\Shlink\Core\Service\ShortUrl;
use Shlinkio\Shlink\Core\Entity\ShortUrl;
use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException;
use Shlinkio\Shlink\Core\Model\ShortUrlIdentifier;
+use Shlinkio\Shlink\Rest\Entity\ApiKey;
interface ShortUrlResolverInterface
{
/**
* @throws ShortUrlNotFoundException
*/
- public function resolveShortUrl(ShortUrlIdentifier $identifier): ShortUrl;
+ public function resolveShortUrl(ShortUrlIdentifier $identifier, ?ApiKey $apiKey = null): ShortUrl;
/**
* @throws ShortUrlNotFoundException
diff --git a/module/Core/src/Service/ShortUrlService.php b/module/Core/src/Service/ShortUrlService.php
index 9159ef63..06b39f08 100644
--- a/module/Core/src/Service/ShortUrlService.php
+++ b/module/Core/src/Service/ShortUrlService.php
@@ -17,6 +17,7 @@ use Shlinkio\Shlink\Core\Repository\ShortUrlRepository;
use Shlinkio\Shlink\Core\Service\ShortUrl\ShortUrlResolverInterface;
use Shlinkio\Shlink\Core\Util\TagManagerTrait;
use Shlinkio\Shlink\Core\Util\UrlValidatorInterface;
+use Shlinkio\Shlink\Rest\Entity\ApiKey;
class ShortUrlService implements ShortUrlServiceInterface
{
@@ -39,11 +40,11 @@ class ShortUrlService implements ShortUrlServiceInterface
/**
* @return ShortUrl[]|Paginator
*/
- public function listShortUrls(ShortUrlsParams $params): Paginator
+ public function listShortUrls(ShortUrlsParams $params, ?ApiKey $apiKey = null): Paginator
{
/** @var ShortUrlRepository $repo */
$repo = $this->em->getRepository(ShortUrl::class);
- $paginator = new Paginator(new ShortUrlRepositoryAdapter($repo, $params));
+ $paginator = new Paginator(new ShortUrlRepositoryAdapter($repo, $params, $apiKey));
$paginator->setItemCountPerPage($params->itemsPerPage())
->setCurrentPageNumber($params->page());
@@ -54,9 +55,9 @@ class ShortUrlService implements ShortUrlServiceInterface
* @param string[] $tags
* @throws ShortUrlNotFoundException
*/
- public function setTagsByShortCode(ShortUrlIdentifier $identifier, array $tags = []): ShortUrl
+ public function setTagsByShortCode(ShortUrlIdentifier $identifier, array $tags, ?ApiKey $apiKey = null): ShortUrl
{
- $shortUrl = $this->urlResolver->resolveShortUrl($identifier);
+ $shortUrl = $this->urlResolver->resolveShortUrl($identifier, $apiKey);
$shortUrl->setTags($this->tagNamesToEntities($this->em, $tags));
$this->em->flush();
@@ -68,13 +69,16 @@ class ShortUrlService implements ShortUrlServiceInterface
* @throws ShortUrlNotFoundException
* @throws InvalidUrlException
*/
- public function updateMetadataByShortCode(ShortUrlIdentifier $identifier, ShortUrlEdit $shortUrlEdit): ShortUrl
- {
+ public function updateMetadataByShortCode(
+ ShortUrlIdentifier $identifier,
+ ShortUrlEdit $shortUrlEdit,
+ ?ApiKey $apiKey = null
+ ): ShortUrl {
if ($shortUrlEdit->hasLongUrl()) {
$this->urlValidator->validateUrl($shortUrlEdit->longUrl(), $shortUrlEdit->doValidateUrl());
}
- $shortUrl = $this->urlResolver->resolveShortUrl($identifier);
+ $shortUrl = $this->urlResolver->resolveShortUrl($identifier, $apiKey);
$shortUrl->update($shortUrlEdit);
$this->em->flush();
diff --git a/module/Core/src/Service/ShortUrlServiceInterface.php b/module/Core/src/Service/ShortUrlServiceInterface.php
index 3c09e7e9..5f6b9b30 100644
--- a/module/Core/src/Service/ShortUrlServiceInterface.php
+++ b/module/Core/src/Service/ShortUrlServiceInterface.php
@@ -11,23 +11,28 @@ use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException;
use Shlinkio\Shlink\Core\Model\ShortUrlEdit;
use Shlinkio\Shlink\Core\Model\ShortUrlIdentifier;
use Shlinkio\Shlink\Core\Model\ShortUrlsParams;
+use Shlinkio\Shlink\Rest\Entity\ApiKey;
interface ShortUrlServiceInterface
{
/**
* @return ShortUrl[]|Paginator
*/
- public function listShortUrls(ShortUrlsParams $params): Paginator;
+ public function listShortUrls(ShortUrlsParams $params, ?ApiKey $apiKey = null): Paginator;
/**
* @param string[] $tags
* @throws ShortUrlNotFoundException
*/
- public function setTagsByShortCode(ShortUrlIdentifier $identifier, array $tags = []): ShortUrl;
+ public function setTagsByShortCode(ShortUrlIdentifier $identifier, array $tags, ?ApiKey $apiKey = null): ShortUrl;
/**
* @throws ShortUrlNotFoundException
* @throws InvalidUrlException
*/
- public function updateMetadataByShortCode(ShortUrlIdentifier $identifier, ShortUrlEdit $shortUrlEdit): ShortUrl;
+ public function updateMetadataByShortCode(
+ ShortUrlIdentifier $identifier,
+ ShortUrlEdit $shortUrlEdit,
+ ?ApiKey $apiKey = null
+ ): ShortUrl;
}
diff --git a/module/Core/src/Service/VisitsTracker.php b/module/Core/src/Service/VisitsTracker.php
index e777af76..46d4bd6b 100644
--- a/module/Core/src/Service/VisitsTracker.php
+++ b/module/Core/src/Service/VisitsTracker.php
@@ -10,7 +10,7 @@ use Psr\EventDispatcher\EventDispatcherInterface;
use Shlinkio\Shlink\Core\Entity\ShortUrl;
use Shlinkio\Shlink\Core\Entity\Tag;
use Shlinkio\Shlink\Core\Entity\Visit;
-use Shlinkio\Shlink\Core\EventDispatcher\ShortUrlVisited;
+use Shlinkio\Shlink\Core\EventDispatcher\Event\ShortUrlVisited;
use Shlinkio\Shlink\Core\Exception\ShortUrlNotFoundException;
use Shlinkio\Shlink\Core\Exception\TagNotFoundException;
use Shlinkio\Shlink\Core\Model\ShortUrlIdentifier;
@@ -21,6 +21,7 @@ use Shlinkio\Shlink\Core\Paginator\Adapter\VisitsPaginatorAdapter;
use Shlinkio\Shlink\Core\Repository\ShortUrlRepositoryInterface;
use Shlinkio\Shlink\Core\Repository\TagRepository;
use Shlinkio\Shlink\Core\Repository\VisitRepositoryInterface;
+use Shlinkio\Shlink\Rest\Entity\ApiKey;
class VisitsTracker implements VisitsTrackerInterface
{
@@ -52,17 +53,19 @@ class VisitsTracker implements VisitsTrackerInterface
* @return Visit[]|Paginator
* @throws ShortUrlNotFoundException
*/
- public function info(ShortUrlIdentifier $identifier, VisitsParams $params): Paginator
+ public function info(ShortUrlIdentifier $identifier, VisitsParams $params, ?ApiKey $apiKey = null): Paginator
{
+ $spec = $apiKey !== null ? $apiKey->spec() : null;
+
/** @var ShortUrlRepositoryInterface $repo */
$repo = $this->em->getRepository(ShortUrl::class);
- if (! $repo->shortCodeIsInUse($identifier->shortCode(), $identifier->domain())) {
+ if (! $repo->shortCodeIsInUse($identifier->shortCode(), $identifier->domain(), $spec)) {
throw ShortUrlNotFoundException::fromNotFound($identifier);
}
/** @var VisitRepositoryInterface $repo */
$repo = $this->em->getRepository(Visit::class);
- $paginator = new Paginator(new VisitsPaginatorAdapter($repo, $identifier, $params));
+ $paginator = new Paginator(new VisitsPaginatorAdapter($repo, $identifier, $params, $spec));
$paginator->setItemCountPerPage($params->getItemsPerPage())
->setCurrentPageNumber($params->getPage());
@@ -73,18 +76,17 @@ class VisitsTracker implements VisitsTrackerInterface
* @return Visit[]|Paginator
* @throws TagNotFoundException
*/
- public function visitsForTag(string $tag, VisitsParams $params): Paginator
+ public function visitsForTag(string $tag, VisitsParams $params, ?ApiKey $apiKey = null): Paginator
{
/** @var TagRepository $tagRepo */
$tagRepo = $this->em->getRepository(Tag::class);
- $count = $tagRepo->count(['name' => $tag]);
- if ($count === 0) {
+ if (! $tagRepo->tagExists($tag, $apiKey)) {
throw TagNotFoundException::fromTag($tag);
}
/** @var VisitRepositoryInterface $repo */
$repo = $this->em->getRepository(Visit::class);
- $paginator = new Paginator(new VisitsForTagPaginatorAdapter($repo, $tag, $params));
+ $paginator = new Paginator(new VisitsForTagPaginatorAdapter($repo, $tag, $params, $apiKey));
$paginator->setItemCountPerPage($params->getItemsPerPage())
->setCurrentPageNumber($params->getPage());
diff --git a/module/Core/src/Service/VisitsTrackerInterface.php b/module/Core/src/Service/VisitsTrackerInterface.php
index 2c2759c2..ecffae23 100644
--- a/module/Core/src/Service/VisitsTrackerInterface.php
+++ b/module/Core/src/Service/VisitsTrackerInterface.php
@@ -12,6 +12,7 @@ use Shlinkio\Shlink\Core\Exception\TagNotFoundException;
use Shlinkio\Shlink\Core\Model\ShortUrlIdentifier;
use Shlinkio\Shlink\Core\Model\Visitor;
use Shlinkio\Shlink\Core\Model\VisitsParams;
+use Shlinkio\Shlink\Rest\Entity\ApiKey;
interface VisitsTrackerInterface
{
@@ -21,11 +22,11 @@ interface VisitsTrackerInterface
* @return Visit[]|Paginator
* @throws ShortUrlNotFoundException
*/
- public function info(ShortUrlIdentifier $identifier, VisitsParams $params): Paginator;
+ public function info(ShortUrlIdentifier $identifier, VisitsParams $params, ?ApiKey $apiKey = null): Paginator;
/**
* @return Visit[]|Paginator
* @throws TagNotFoundException
*/
- public function visitsForTag(string $tag, VisitsParams $params): Paginator;
+ public function visitsForTag(string $tag, VisitsParams $params, ?ApiKey $apiKey = null): Paginator;
}
diff --git a/module/Core/src/ShortUrl/Resolver/PersistenceShortUrlRelationResolver.php b/module/Core/src/ShortUrl/Resolver/PersistenceShortUrlRelationResolver.php
index d898fb37..0e3afa23 100644
--- a/module/Core/src/ShortUrl/Resolver/PersistenceShortUrlRelationResolver.php
+++ b/module/Core/src/ShortUrl/Resolver/PersistenceShortUrlRelationResolver.php
@@ -6,7 +6,6 @@ namespace Shlinkio\Shlink\Core\ShortUrl\Resolver;
use Doctrine\ORM\EntityManagerInterface;
use Shlinkio\Shlink\Core\Entity\Domain;
-use Shlinkio\Shlink\Rest\Entity\ApiKey;
class PersistenceShortUrlRelationResolver implements ShortUrlRelationResolverInterface
{
@@ -27,15 +26,4 @@ class PersistenceShortUrlRelationResolver implements ShortUrlRelationResolverInt
$existingDomain = $this->em->getRepository(Domain::class)->findOneBy(['authority' => $domain]);
return $existingDomain ?? new Domain($domain);
}
-
- public function resolveApiKey(?string $key): ?ApiKey
- {
- if ($key === null) {
- return null;
- }
-
- /** @var ApiKey|null $existingApiKey */
- $existingApiKey = $this->em->getRepository(ApiKey::class)->findOneBy(['key' => $key]);
- return $existingApiKey;
- }
}
diff --git a/module/Core/src/ShortUrl/Resolver/ShortUrlRelationResolverInterface.php b/module/Core/src/ShortUrl/Resolver/ShortUrlRelationResolverInterface.php
index 0a708cf6..bc576dbd 100644
--- a/module/Core/src/ShortUrl/Resolver/ShortUrlRelationResolverInterface.php
+++ b/module/Core/src/ShortUrl/Resolver/ShortUrlRelationResolverInterface.php
@@ -5,11 +5,8 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Core\ShortUrl\Resolver;
use Shlinkio\Shlink\Core\Entity\Domain;
-use Shlinkio\Shlink\Rest\Entity\ApiKey;
interface ShortUrlRelationResolverInterface
{
public function resolveDomain(?string $domain): ?Domain;
-
- public function resolveApiKey(?string $key): ?ApiKey;
}
diff --git a/module/Core/src/ShortUrl/Resolver/SimpleShortUrlRelationResolver.php b/module/Core/src/ShortUrl/Resolver/SimpleShortUrlRelationResolver.php
index 9de156ee..4e4620f5 100644
--- a/module/Core/src/ShortUrl/Resolver/SimpleShortUrlRelationResolver.php
+++ b/module/Core/src/ShortUrl/Resolver/SimpleShortUrlRelationResolver.php
@@ -5,7 +5,6 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Core\ShortUrl\Resolver;
use Shlinkio\Shlink\Core\Entity\Domain;
-use Shlinkio\Shlink\Rest\Entity\ApiKey;
class SimpleShortUrlRelationResolver implements ShortUrlRelationResolverInterface
{
@@ -13,9 +12,4 @@ class SimpleShortUrlRelationResolver implements ShortUrlRelationResolverInterfac
{
return $domain !== null ? new Domain($domain) : null;
}
-
- public function resolveApiKey(?string $key): ?ApiKey
- {
- return null;
- }
}
diff --git a/module/Core/src/ShortUrl/Spec/BelongsToApiKey.php b/module/Core/src/ShortUrl/Spec/BelongsToApiKey.php
new file mode 100644
index 00000000..9e094b90
--- /dev/null
+++ b/module/Core/src/ShortUrl/Spec/BelongsToApiKey.php
@@ -0,0 +1,28 @@
+apiKey = $apiKey;
+ $this->dqlAlias = $dqlAlias ?? 's';
+ parent::__construct($this->dqlAlias);
+ }
+
+ protected function getSpec(): Filter
+ {
+ return Spec::eq('authorApiKey', $this->apiKey, $this->dqlAlias);
+ }
+}
diff --git a/module/Core/src/ShortUrl/Spec/BelongsToApiKeyInlined.php b/module/Core/src/ShortUrl/Spec/BelongsToApiKeyInlined.php
new file mode 100644
index 00000000..197031f3
--- /dev/null
+++ b/module/Core/src/ShortUrl/Spec/BelongsToApiKeyInlined.php
@@ -0,0 +1,29 @@
+apiKey = $apiKey;
+ }
+
+ public function getFilter(QueryBuilder $qb, string $dqlAlias): string
+ {
+ // Parameters in this query need to be inlined, not bound, as we need to use it as sub-query later
+ return (string) $qb->expr()->eq('s.authorApiKey', '\'' . $this->apiKey->getId() . '\'');
+ }
+
+ public function modify(QueryBuilder $qb, string $dqlAlias): void
+ {
+ }
+}
diff --git a/module/Core/src/ShortUrl/Spec/BelongsToDomain.php b/module/Core/src/ShortUrl/Spec/BelongsToDomain.php
new file mode 100644
index 00000000..81b4388a
--- /dev/null
+++ b/module/Core/src/ShortUrl/Spec/BelongsToDomain.php
@@ -0,0 +1,27 @@
+domainId = $domainId;
+ $this->dqlAlias = $dqlAlias ?? 's';
+ parent::__construct($this->dqlAlias);
+ }
+
+ protected function getSpec(): Filter
+ {
+ return Spec::eq('domain', $this->domainId, $this->dqlAlias);
+ }
+}
diff --git a/module/Core/src/ShortUrl/Spec/BelongsToDomainInlined.php b/module/Core/src/ShortUrl/Spec/BelongsToDomainInlined.php
new file mode 100644
index 00000000..a8ef527e
--- /dev/null
+++ b/module/Core/src/ShortUrl/Spec/BelongsToDomainInlined.php
@@ -0,0 +1,28 @@
+domainId = $domainId;
+ }
+
+ public function getFilter(QueryBuilder $qb, string $dqlAlias): string
+ {
+ // Parameters in this query need to be inlined, not bound, as we need to use it as sub-query later
+ return (string) $qb->expr()->eq('s.domain', '\'' . $this->domainId . '\'');
+ }
+
+ public function modify(QueryBuilder $qb, string $dqlAlias): void
+ {
+ }
+}
diff --git a/module/Core/src/Tag/Model/TagRenaming.php b/module/Core/src/Tag/Model/TagRenaming.php
new file mode 100644
index 00000000..1f677376
--- /dev/null
+++ b/module/Core/src/Tag/Model/TagRenaming.php
@@ -0,0 +1,68 @@
+oldName = $oldName;
+ $o->newName = $newName;
+
+ return $o;
+ }
+
+ public static function fromArray(array $payload): self
+ {
+ if (! isset($payload['oldName'], $payload['newName'])) {
+ throw ValidationException::fromArray([
+ 'oldName' => 'oldName is required',
+ 'newName' => 'newName is required',
+ ]);
+ }
+
+ return self::fromNames($payload['oldName'], $payload['newName']);
+ }
+
+ public function oldName(): string
+ {
+ return $this->oldName;
+ }
+
+ public function newName(): string
+ {
+ return $this->newName;
+ }
+
+ public function nameChanged(): bool
+ {
+ return $this->oldName !== $this->newName;
+ }
+
+ public function toString(): string
+ {
+ return sprintf('%s to %s', $this->oldName, $this->newName);
+ }
+
+ public function toArray(): array
+ {
+ return [
+ 'oldName' => $this->oldName,
+ 'newName' => $this->newName,
+ ];
+ }
+}
diff --git a/module/Core/src/Tag/Spec/CountTagsWithName.php b/module/Core/src/Tag/Spec/CountTagsWithName.php
new file mode 100644
index 00000000..a3f90a78
--- /dev/null
+++ b/module/Core/src/Tag/Spec/CountTagsWithName.php
@@ -0,0 +1,30 @@
+tagName = $tagName;
+ }
+
+ protected function getSpec(): Specification
+ {
+ return Spec::countOf(
+ Spec::andX(
+ Spec::select('id'),
+ Spec::eq('name', $this->tagName),
+ ),
+ );
+ }
+}
diff --git a/module/Core/src/Tag/TagService.php b/module/Core/src/Tag/TagService.php
index 4e0261a5..ae46a312 100644
--- a/module/Core/src/Tag/TagService.php
+++ b/module/Core/src/Tag/TagService.php
@@ -6,13 +6,18 @@ namespace Shlinkio\Shlink\Core\Tag;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM;
+use Happyr\DoctrineSpecification\Spec;
use Shlinkio\Shlink\Core\Entity\Tag;
+use Shlinkio\Shlink\Core\Exception\ForbiddenTagOperationException;
use Shlinkio\Shlink\Core\Exception\TagConflictException;
use Shlinkio\Shlink\Core\Exception\TagNotFoundException;
use Shlinkio\Shlink\Core\Repository\TagRepository;
use Shlinkio\Shlink\Core\Repository\TagRepositoryInterface;
use Shlinkio\Shlink\Core\Tag\Model\TagInfo;
+use Shlinkio\Shlink\Core\Tag\Model\TagRenaming;
use Shlinkio\Shlink\Core\Util\TagManagerTrait;
+use Shlinkio\Shlink\Rest\ApiKey\Spec\WithApiKeySpecsEnsuringJoin;
+use Shlinkio\Shlink\Rest\Entity\ApiKey;
class TagService implements TagServiceInterface
{
@@ -28,28 +33,38 @@ class TagService implements TagServiceInterface
/**
* @return Tag[]
*/
- public function listTags(): array
+ public function listTags(?ApiKey $apiKey = null): array
{
+ /** @var TagRepository $repo */
+ $repo = $this->em->getRepository(Tag::class);
/** @var Tag[] $tags */
- $tags = $this->em->getRepository(Tag::class)->findBy([], ['name' => 'ASC']);
+ $tags = $repo->match(Spec::andX(
+ Spec::orderBy('name'),
+ new WithApiKeySpecsEnsuringJoin($apiKey),
+ ));
return $tags;
}
/**
* @return TagInfo[]
*/
- public function tagsInfo(): array
+ public function tagsInfo(?ApiKey $apiKey = null): array
{
/** @var TagRepositoryInterface $repo */
$repo = $this->em->getRepository(Tag::class);
- return $repo->findTagsWithInfo();
+ return $repo->findTagsWithInfo($apiKey !== null ? $apiKey->spec() : null);
}
/**
* @param string[] $tagNames
+ * @throws ForbiddenTagOperationException
*/
- public function deleteTags(array $tagNames): void
+ public function deleteTags(array $tagNames, ?ApiKey $apiKey = null): void
{
+ if ($apiKey !== null && ! $apiKey->isAdmin()) {
+ throw ForbiddenTagOperationException::forDeletion();
+ }
+
/** @var TagRepository $repo */
$repo = $this->em->getRepository(Tag::class);
$repo->deleteByName($tagNames);
@@ -73,24 +88,29 @@ class TagService implements TagServiceInterface
/**
* @throws TagNotFoundException
* @throws TagConflictException
+ * @throws ForbiddenTagOperationException
*/
- public function renameTag(string $oldName, string $newName): Tag
+ public function renameTag(TagRenaming $renaming, ?ApiKey $apiKey = null): Tag
{
+ if ($apiKey !== null && ! $apiKey->isAdmin()) {
+ throw ForbiddenTagOperationException::forRenaming();
+ }
+
/** @var TagRepository $repo */
$repo = $this->em->getRepository(Tag::class);
/** @var Tag|null $tag */
- $tag = $repo->findOneBy(['name' => $oldName]);
+ $tag = $repo->findOneBy(['name' => $renaming->oldName()]);
if ($tag === null) {
- throw TagNotFoundException::fromTag($oldName);
+ throw TagNotFoundException::fromTag($renaming->oldName());
}
- $newNameExists = $newName !== $oldName && $repo->count(['name' => $newName]) > 0;
+ $newNameExists = $renaming->nameChanged() && $repo->count(['name' => $renaming->newName()]) > 0;
if ($newNameExists) {
- throw TagConflictException::fromExistingTag($oldName, $newName);
+ throw TagConflictException::forExistingTag($renaming);
}
- $tag->rename($newName);
+ $tag->rename($renaming->newName());
$this->em->flush();
return $tag;
diff --git a/module/Core/src/Tag/TagServiceInterface.php b/module/Core/src/Tag/TagServiceInterface.php
index 3c8c6e69..34cf1871 100644
--- a/module/Core/src/Tag/TagServiceInterface.php
+++ b/module/Core/src/Tag/TagServiceInterface.php
@@ -6,26 +6,30 @@ namespace Shlinkio\Shlink\Core\Tag;
use Doctrine\Common\Collections\Collection;
use Shlinkio\Shlink\Core\Entity\Tag;
+use Shlinkio\Shlink\Core\Exception\ForbiddenTagOperationException;
use Shlinkio\Shlink\Core\Exception\TagConflictException;
use Shlinkio\Shlink\Core\Exception\TagNotFoundException;
use Shlinkio\Shlink\Core\Tag\Model\TagInfo;
+use Shlinkio\Shlink\Core\Tag\Model\TagRenaming;
+use Shlinkio\Shlink\Rest\Entity\ApiKey;
interface TagServiceInterface
{
/**
* @return Tag[]
*/
- public function listTags(): array;
+ public function listTags(?ApiKey $apiKey = null): array;
/**
* @return TagInfo[]
*/
- public function tagsInfo(): array;
+ public function tagsInfo(?ApiKey $apiKey = null): array;
/**
* @param string[] $tagNames
+ * @throws ForbiddenTagOperationException
*/
- public function deleteTags(array $tagNames): void;
+ public function deleteTags(array $tagNames, ?ApiKey $apiKey = null): void;
/**
* @deprecated
@@ -37,6 +41,7 @@ interface TagServiceInterface
/**
* @throws TagNotFoundException
* @throws TagConflictException
+ * @throws ForbiddenTagOperationException
*/
- public function renameTag(string $oldName, string $newName): Tag;
+ public function renameTag(TagRenaming $renaming, ?ApiKey $apiKey = null): Tag;
}
diff --git a/module/Core/src/Validation/ShortUrlMetaInputFilter.php b/module/Core/src/Validation/ShortUrlMetaInputFilter.php
index e3b630e4..ca29ad14 100644
--- a/module/Core/src/Validation/ShortUrlMetaInputFilter.php
+++ b/module/Core/src/Validation/ShortUrlMetaInputFilter.php
@@ -11,6 +11,7 @@ use Laminas\InputFilter\InputFilter;
use Laminas\Validator;
use Shlinkio\Shlink\Common\Validation;
use Shlinkio\Shlink\Core\Util\CocurSymfonySluggerBridge;
+use Shlinkio\Shlink\Rest\Entity\ApiKey;
use const Shlinkio\Shlink\Core\CUSTOM_SLUGS_REGEXP;
use const Shlinkio\Shlink\Core\MIN_SHORT_CODES_LENGTH;
@@ -54,6 +55,7 @@ class ShortUrlMetaInputFilter extends InputFilter
$customSlug->getFilterChain()->attach(new Validation\SluggerFilter(new CocurSymfonySluggerBridge(new Slugify([
'regexp' => CUSTOM_SLUGS_REGEXP,
'lowercase' => false, // We want to keep it case sensitive
+ 'rulesets' => ['default'],
]))));
$customSlug->getValidatorChain()->attach(new Validator\NotEmpty([
Validator\NotEmpty::STRING,
@@ -72,7 +74,11 @@ class ShortUrlMetaInputFilter extends InputFilter
$domain->getValidatorChain()->attach(new Validation\HostAndPortValidator());
$this->add($domain);
- $this->add($this->createInput(self::API_KEY, false));
+ $apiKeyInput = new Input(self::API_KEY);
+ $apiKeyInput
+ ->setRequired(false)
+ ->getValidatorChain()->attach(new Validator\IsInstanceOf(['className' => ApiKey::class]));
+ $this->add($apiKeyInput);
}
private function createPositiveNumberInput(string $name, int $min = 1): Input
diff --git a/module/Core/src/Visit/VisitsStatsHelper.php b/module/Core/src/Visit/VisitsStatsHelper.php
index de3219ff..ab06079a 100644
--- a/module/Core/src/Visit/VisitsStatsHelper.php
+++ b/module/Core/src/Visit/VisitsStatsHelper.php
@@ -8,6 +8,7 @@ use Doctrine\ORM\EntityManagerInterface;
use Shlinkio\Shlink\Core\Entity\Visit;
use Shlinkio\Shlink\Core\Repository\VisitRepository;
use Shlinkio\Shlink\Core\Visit\Model\VisitsStats;
+use Shlinkio\Shlink\Rest\Entity\ApiKey;
class VisitsStatsHelper implements VisitsStatsHelperInterface
{
@@ -18,15 +19,15 @@ class VisitsStatsHelper implements VisitsStatsHelperInterface
$this->em = $em;
}
- public function getVisitsStats(): VisitsStats
+ public function getVisitsStats(?ApiKey $apiKey = null): VisitsStats
{
- return new VisitsStats($this->getVisitsCount());
+ return new VisitsStats($this->getVisitsCount($apiKey));
}
- private function getVisitsCount(): int
+ private function getVisitsCount(?ApiKey $apiKey): int
{
/** @var VisitRepository $visitsRepo */
$visitsRepo = $this->em->getRepository(Visit::class);
- return $visitsRepo->count([]);
+ return $visitsRepo->countVisits($apiKey);
}
}
diff --git a/module/Core/src/Visit/VisitsStatsHelperInterface.php b/module/Core/src/Visit/VisitsStatsHelperInterface.php
index 81423cb0..ca044d4b 100644
--- a/module/Core/src/Visit/VisitsStatsHelperInterface.php
+++ b/module/Core/src/Visit/VisitsStatsHelperInterface.php
@@ -5,8 +5,9 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Core\Visit;
use Shlinkio\Shlink\Core\Visit\Model\VisitsStats;
+use Shlinkio\Shlink\Rest\Entity\ApiKey;
interface VisitsStatsHelperInterface
{
- public function getVisitsStats(): VisitsStats;
+ public function getVisitsStats(?ApiKey $apiKey = null): VisitsStats;
}
diff --git a/module/Core/templates/404.html b/module/Core/templates/404.html
new file mode 100644
index 00000000..93e6fb64
--- /dev/null
+++ b/module/Core/templates/404.html
@@ -0,0 +1,27 @@
+
+
+
+ Not Found | Shlink
+
+
+
+
+
+
+
+
+