mirror of
https://github.com/archtechx/tenancy.git
synced 2026-02-05 16:54:05 +00:00
Merge branch 'master' into stein-j/3.x
This commit is contained in:
commit
147b2fe3c0
149 changed files with 1989 additions and 1034 deletions
81
.github/workflows/ci.yml
vendored
81
.github/workflows/ci.yml
vendored
|
|
@ -1,32 +1,91 @@
|
||||||
name: CI
|
name: CI
|
||||||
|
|
||||||
env:
|
env:
|
||||||
COMPOSE_INTERACTIVE_NO_CLI: 1
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [ master ]
|
|
||||||
pull_request:
|
pull_request:
|
||||||
branches: [ master ]
|
branches: [ master ]
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
tests:
|
tests:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
container: archtechx/tenancy:latest
|
||||||
|
|
||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
php: ["8.1"]
|
laravel: ['^9.0']
|
||||||
laravel: ["^9.0"]
|
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- name: Checkout
|
||||||
- name: Start docker containers
|
uses: actions/checkout@v2
|
||||||
run: PHP_VERSION=${{ matrix.php }} docker-compose up -d
|
|
||||||
- name: Install dependencies
|
- name: Install Composer dependencies
|
||||||
run: docker-compose exec -T test composer require --no-interaction "laravel/framework:${{ matrix.laravel }}"
|
run: |
|
||||||
- name: Run tests
|
composer require "laravel/framework:${{ matrix.laravel }}" --no-interaction --no-update
|
||||||
run: ./test
|
composer update --prefer-dist --no-interaction
|
||||||
|
- name: Run tests
|
||||||
|
run: ./vendor/bin/pest
|
||||||
|
env:
|
||||||
|
DB_PASSWORD: password
|
||||||
|
DB_USERNAME: root
|
||||||
|
DB_DATABASE: main
|
||||||
|
TENANCY_TEST_MYSQL_HOST: mysql
|
||||||
|
TENANCY_TEST_PGSQL_HOST: postgres
|
||||||
|
TENANCY_TEST_REDIS_HOST: redis
|
||||||
|
TENANCY_TEST_SQLSRV_HOST: mssql
|
||||||
|
|
||||||
|
- name: Upload coverage to Codecov
|
||||||
|
uses: codecov/codecov-action@v2
|
||||||
|
with:
|
||||||
|
token: 24382d15-84e7-4a55-bea4-c4df96a24a9b
|
||||||
|
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:latest
|
||||||
|
env:
|
||||||
|
POSTGRES_PASSWORD: password
|
||||||
|
POSTGRES_USER: root
|
||||||
|
POSTGRES_DB: main
|
||||||
|
ports:
|
||||||
|
- 5432/tcp
|
||||||
|
options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 3
|
||||||
|
|
||||||
|
mysql:
|
||||||
|
image: mysql:5.7
|
||||||
|
env:
|
||||||
|
MYSQL_ALLOW_EMPTY_PASSWORD: false
|
||||||
|
MYSQL_ROOT_PASSWORD: password
|
||||||
|
MYSQL_DATABASE: main
|
||||||
|
ports:
|
||||||
|
- 3306/tcp
|
||||||
|
options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3
|
||||||
|
|
||||||
|
mysql2:
|
||||||
|
image: mysql:5.7
|
||||||
|
env:
|
||||||
|
MYSQL_ALLOW_EMPTY_PASSWORD: false
|
||||||
|
MYSQL_ROOT_PASSWORD: password
|
||||||
|
MYSQL_DATABASE: main
|
||||||
|
ports:
|
||||||
|
- 3306/tcp
|
||||||
|
options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3
|
||||||
|
|
||||||
|
mssql:
|
||||||
|
image: mcr.microsoft.com/mssql/server:2019-latest
|
||||||
|
ports:
|
||||||
|
- 1433/tcp
|
||||||
|
env:
|
||||||
|
ACCEPT_EULA: Y
|
||||||
|
SA_PASSWORD: P@ssword
|
||||||
|
options: --health-cmd "echo quit | /opt/mssql-tools/bin/sqlcmd -S 127.0.0.1 -l 1 -U sa -P P@ssword"
|
||||||
|
|
||||||
|
redis:
|
||||||
|
image: redis
|
||||||
|
ports:
|
||||||
|
- 6379/tcp
|
||||||
|
options: --health-cmd="redis-cli ping" --health-interval=10s --health-timeout=5s --health-retries=3
|
||||||
|
|
||||||
php-cs-fixer:
|
php-cs-fixer:
|
||||||
name: Code style (php-cs-fixer)
|
name: Code style (php-cs-fixer)
|
||||||
|
|
|
||||||
|
|
@ -8,8 +8,24 @@ php-cs-fixer will fix code style violations in your pull requests.
|
||||||
|
|
||||||
Run `composer docker-up` to start the containers. Then run `composer test` to run the tests.
|
Run `composer docker-up` to start the containers. Then run `composer test` to run the tests.
|
||||||
|
|
||||||
|
If you need to pass additional flags to phpunit, use `./test --foo` instead of `composer test --foo`. Composer scripts unfortunately don't pass CLI arguments.
|
||||||
|
|
||||||
When you're done testing, run `composer docker-down` to shut down the containers.
|
When you're done testing, run `composer docker-down` to shut down the containers.
|
||||||
|
|
||||||
### Docker on M1
|
### Docker on M1
|
||||||
|
|
||||||
Run `composer docker-m1` to symlink `docker-compose-m1.override.yml` to `docker-compose.override.yml`. This will reconfigure a few services in the docker compose config to be compatible with M1.
|
Run `composer docker-m1` to symlink `docker-compose-m1.override.yml` to `docker-compose.override.yml`. This will reconfigure a few services in the docker compose config to be compatible with M1.
|
||||||
|
|
||||||
|
### Coverage reports
|
||||||
|
|
||||||
|
To run tests and generate coverage reports, use `composer test-full`.
|
||||||
|
|
||||||
|
To view the coverage reports in your browser, use `composer coverage` (works on macOS; on other operating systems you can manually open `coverage/phpunit/html/index.html` in your browser).
|
||||||
|
|
||||||
|
### Rebuilding containers
|
||||||
|
|
||||||
|
If you need to rebuild the container for any reason (e.g. a change in `Dockerfile`), you can use `composer docker-rebuild`.
|
||||||
|
|
||||||
|
## PHPStan
|
||||||
|
|
||||||
|
Use `composer phpstan` to run our phpstan suite.
|
||||||
|
|
|
||||||
65
Dockerfile
65
Dockerfile
|
|
@ -1,59 +1,42 @@
|
||||||
ARG PHP_VERSION=7.4
|
# add amd64 platform to support Mac M1
|
||||||
ARG PHP_TARGET=php:${PHP_VERSION}-cli
|
FROM --platform=linux/amd64 shivammathur/node:latest-amd64
|
||||||
|
|
||||||
FROM --platform=linux/amd64 ${PHP_TARGET}
|
ARG PHP_VERSION=8.1
|
||||||
|
|
||||||
ARG COMPOSER_TARGET=2.0.3
|
|
||||||
|
|
||||||
WORKDIR /var/www/html
|
WORKDIR /var/www/html
|
||||||
|
|
||||||
LABEL org.opencontainers.image.source=https://github.com/stancl/tenancy \
|
|
||||||
org.opencontainers.image.vendor="Samuel Štancl" \
|
|
||||||
org.opencontainers.image.licenses="MIT" \
|
|
||||||
org.opencontainers.image.title="PHP ${PHP_VERSION} with modules for laravel support" \
|
|
||||||
org.opencontainers.image.description="PHP ${PHP_VERSION} with a set of php/os packages suitable for running Laravel apps"
|
|
||||||
|
|
||||||
# our default timezone and langauge
|
# our default timezone and langauge
|
||||||
ENV TZ=Europe/London
|
ENV TZ=Europe/London
|
||||||
ENV LANG=en_GB.UTF-8
|
ENV LANG=en_GB.UTF-8
|
||||||
|
|
||||||
# Note: we only install reliable/core 1st-party php extensions here.
|
# install MYSSQL ODBC Driver
|
||||||
# If your app needs custom ones install them in the apps own
|
|
||||||
# Dockerfile _and pin the versions_! Eg:
|
|
||||||
# RUN pecl install memcached-2.2.0 && docker-php-ext-enable memcached
|
|
||||||
|
|
||||||
|
|
||||||
RUN apt-get update \
|
RUN apt-get update \
|
||||||
&& apt-get install -y gnupg2 \
|
&& apt-get install -y gnupg2 \
|
||||||
&& curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - \
|
&& curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - \
|
||||||
&& curl https://packages.microsoft.com/config/debian/11/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 \
|
&& apt-get update \
|
||||||
&& ACCEPT_EULA=Y apt-get install -y unixodbc-dev msodbcsql17
|
&& ACCEPT_EULA=Y apt-get install -y unixodbc-dev msodbcsql17
|
||||||
|
|
||||||
RUN apt-get install -y --no-install-recommends locales apt-transport-https libfreetype6-dev libjpeg62-turbo-dev libpng-dev libgmp-dev libldap2-dev netcat curl mariadb-client sqlite3 libsqlite3-dev libpq-dev libzip-dev unzip vim-tiny gosu git
|
# set PHP version
|
||||||
|
RUN update-alternatives --set php /usr/bin/php$PHP_VERSION \
|
||||||
|
&& update-alternatives --set phar /usr/bin/phar$PHP_VERSION \
|
||||||
|
&& update-alternatives --set phar.phar /usr/bin/phar.phar$PHP_VERSION \
|
||||||
|
&& update-alternatives --set phpize /usr/bin/phpize$PHP_VERSION \
|
||||||
|
&& update-alternatives --set php-config /usr/bin/php-config$PHP_VERSION
|
||||||
|
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends libhiredis0.14 libjemalloc2 liblua5.1-0 lua-bitop lua-cjson redis redis-server redis-tools
|
||||||
|
|
||||||
|
RUN pecl install redis-5.3.7 sqlsrv pdo_sqlsrv pcov \
|
||||||
|
&& printf "; priority=20\nextension=redis.so\n" > /etc/php/$PHP_VERSION/mods-available/redis.ini \
|
||||||
|
&& printf "; priority=20\nextension=sqlsrv.so\n" > /etc/php/$PHP_VERSION/mods-available/sqlsrv.ini \
|
||||||
|
&& printf "; priority=30\nextension=pdo_sqlsrv.so\n" > /etc/php/$PHP_VERSION/mods-available/pdo_sqlsrv.ini \
|
||||||
|
&& printf "; priority=40\nextension=pcov.so\n" > /etc/php/$PHP_VERSION/mods-available/pcov.ini \
|
||||||
|
&& phpenmod -v $PHP_VERSION redis sqlsrv pdo_sqlsrv pcov
|
||||||
|
|
||||||
|
# install composer
|
||||||
|
COPY --from=composer:latest /usr/bin/composer /usr/local/bin/composer
|
||||||
|
|
||||||
RUN docker-php-ext-configure pgsql -with-pgsql=/usr/local/pgsql \
|
|
||||||
# && if [ "${PHP_VERSION}" = "7.4" ]; then docker-php-ext-configure gd --with-freetype --with-jpeg; else docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/; fi \
|
|
||||||
&& docker-php-ext-install -j$(nproc) gd pdo pdo_mysql pdo_pgsql pdo_sqlite pgsql zip gmp bcmath pcntl ldap sysvmsg exif \
|
|
||||||
# install the redis php extension
|
|
||||||
&& pecl install redis-5.3.7 \
|
|
||||||
&& docker-php-ext-enable redis \
|
|
||||||
# install the pcov extention
|
|
||||||
&& pecl install pcov \
|
|
||||||
&& docker-php-ext-enable pcov \
|
|
||||||
&& echo "pcov.enabled = 1" > /usr/local/etc/php/conf.d/pcov.ini \
|
|
||||||
# install sqlsrv
|
|
||||||
&& pecl install sqlsrv pdo_sqlsrv \
|
|
||||||
&& docker-php-ext-enable sqlsrv pdo_sqlsrv
|
|
||||||
# clear the apt cache
|
|
||||||
RUN rm -rf /var/lib/apt/lists/* \
|
|
||||||
&& rm -rf /var/lib/apt/lists/* \
|
|
||||||
# install composer
|
|
||||||
&& curl -o /tmp/composer-setup.php https://getcomposer.org/installer \
|
|
||||||
&& curl -o /tmp/composer-setup.sig https://composer.github.io/installer.sig \
|
|
||||||
&& php -r "if (hash('SHA384', file_get_contents('/tmp/composer-setup.php')) !== trim(file_get_contents('/tmp/composer-setup.sig'))) { unlink('/tmp/composer-setup.php'); echo 'Invalid installer' . PHP_EOL; exit(1); }" \
|
|
||||||
&& php /tmp/composer-setup.php --version=${COMPOSER_TARGET} --no-ansi --install-dir=/usr/local/bin --filename=composer --snapshot \
|
|
||||||
&& rm -f /tmp/composer-setup.*
|
|
||||||
# set the system timezone
|
# set the system timezone
|
||||||
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime \
|
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime \
|
||||||
&& echo $TZ > /etc/timezone
|
&& echo $TZ > /etc/timezone
|
||||||
|
|
|
||||||
|
|
@ -28,6 +28,7 @@ class TenancyServiceProvider extends ServiceProvider
|
||||||
Jobs\CreateDatabase::class,
|
Jobs\CreateDatabase::class,
|
||||||
Jobs\MigrateDatabase::class,
|
Jobs\MigrateDatabase::class,
|
||||||
// Jobs\SeedDatabase::class,
|
// Jobs\SeedDatabase::class,
|
||||||
|
Jobs\CreateStorageSymlinks::class,
|
||||||
|
|
||||||
// Your own jobs to prepare the tenant.
|
// Your own jobs to prepare the tenant.
|
||||||
// Provision API keys, create S3 buckets, anything you want!
|
// Provision API keys, create S3 buckets, anything you want!
|
||||||
|
|
@ -46,10 +47,13 @@ class TenancyServiceProvider extends ServiceProvider
|
||||||
])->send(function (Events\DeletingTenant $event) {
|
])->send(function (Events\DeletingTenant $event) {
|
||||||
return $event->tenant;
|
return $event->tenant;
|
||||||
})->shouldBeQueued(false),
|
})->shouldBeQueued(false),
|
||||||
|
|
||||||
|
// Listeners\DeleteTenantStorage::class,
|
||||||
],
|
],
|
||||||
Events\TenantDeleted::class => [
|
Events\TenantDeleted::class => [
|
||||||
JobPipeline::make([
|
JobPipeline::make([
|
||||||
Jobs\DeleteDatabase::class,
|
Jobs\DeleteDatabase::class,
|
||||||
|
Jobs\RemoveStorageSymlinks::class,
|
||||||
])->send(function (Events\TenantDeleted $event) {
|
])->send(function (Events\TenantDeleted $event) {
|
||||||
return $event->tenant;
|
return $event->tenant;
|
||||||
})->shouldBeQueued(false), // `false` by default, but you probably want to make this `true` for production.
|
})->shouldBeQueued(false), // `false` by default, but you probably want to make this `true` for production.
|
||||||
|
|
@ -93,6 +97,12 @@ class TenancyServiceProvider extends ServiceProvider
|
||||||
Listeners\UpdateSyncedResource::class,
|
Listeners\UpdateSyncedResource::class,
|
||||||
],
|
],
|
||||||
|
|
||||||
|
// Storage symlinks
|
||||||
|
Events\CreatingStorageSymlink::class => [],
|
||||||
|
Events\StorageSymlinkCreated::class => [],
|
||||||
|
Events\RemovingStorageSymlink::class => [],
|
||||||
|
Events\StorageSymlinkRemoved::class => [],
|
||||||
|
|
||||||
// Fired only when a synced resource is changed in a different DB than the origin DB (to avoid infinite loops)
|
// Fired only when a synced resource is changed in a different DB than the origin DB (to avoid infinite loops)
|
||||||
Events\SyncedResourceChangedInForeignDatabase::class => [],
|
Events\SyncedResourceChangedInForeignDatabase::class => [],
|
||||||
];
|
];
|
||||||
|
|
|
||||||
|
|
@ -32,6 +32,7 @@ return [
|
||||||
Stancl\Tenancy\Bootstrappers\CacheTenancyBootstrapper::class,
|
Stancl\Tenancy\Bootstrappers\CacheTenancyBootstrapper::class,
|
||||||
Stancl\Tenancy\Bootstrappers\FilesystemTenancyBootstrapper::class,
|
Stancl\Tenancy\Bootstrappers\FilesystemTenancyBootstrapper::class,
|
||||||
Stancl\Tenancy\Bootstrappers\QueueTenancyBootstrapper::class,
|
Stancl\Tenancy\Bootstrappers\QueueTenancyBootstrapper::class,
|
||||||
|
Stancl\Tenancy\Bootstrappers\BatchTenancyBootstrapper::class,
|
||||||
// Stancl\Tenancy\Bootstrappers\RedisTenancyBootstrapper::class, // Note: phpredis is needed
|
// Stancl\Tenancy\Bootstrappers\RedisTenancyBootstrapper::class, // Note: phpredis is needed
|
||||||
],
|
],
|
||||||
|
|
||||||
|
|
@ -58,22 +59,22 @@ return [
|
||||||
* TenantDatabaseManagers are classes that handle the creation & deletion of tenant databases.
|
* TenantDatabaseManagers are classes that handle the creation & deletion of tenant databases.
|
||||||
*/
|
*/
|
||||||
'managers' => [
|
'managers' => [
|
||||||
'sqlite' => Stancl\Tenancy\TenantDatabaseManagers\SQLiteDatabaseManager::class,
|
'sqlite' => Stancl\Tenancy\Database\TenantDatabaseManagers\SQLiteDatabaseManager::class,
|
||||||
'mysql' => Stancl\Tenancy\TenantDatabaseManagers\MySQLDatabaseManager::class,
|
'mysql' => Stancl\Tenancy\Database\TenantDatabaseManagers\MySQLDatabaseManager::class,
|
||||||
'pgsql' => Stancl\Tenancy\TenantDatabaseManagers\PostgreSQLDatabaseManager::class,
|
'pgsql' => Stancl\Tenancy\Database\TenantDatabaseManagers\PostgreSQLDatabaseManager::class,
|
||||||
'sqlsrv' => Stancl\Tenancy\TenantDatabaseManagers\MicrosoftSQLDatabaseManager::class,
|
'sqlsrv' => Stancl\Tenancy\Database\TenantDatabaseManagers\MicrosoftSQLDatabaseManager::class,
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Use this database manager for MySQL to have a DB user created for each tenant database.
|
* Use this database manager for MySQL to have a DB user created for each tenant database.
|
||||||
* You can customize the grants given to these users by changing the $grants property.
|
* You can customize the grants given to these users by changing the $grants property.
|
||||||
*/
|
*/
|
||||||
// 'mysql' => Stancl\Tenancy\TenantDatabaseManagers\PermissionControlledMySQLDatabaseManager::class,
|
// 'mysql' => Stancl\Tenancy\Database\TenantDatabaseManagers\PermissionControlledMySQLDatabaseManager::class,
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Disable the pgsql manager above, and enable the one below if you
|
* Disable the pgsql manager above, and enable the one below if you
|
||||||
* want to separate tenant DBs by schemas rather than databases.
|
* want to separate tenant DBs by schemas rather than databases.
|
||||||
*/
|
*/
|
||||||
// 'pgsql' => Stancl\Tenancy\TenantDatabaseManagers\PostgreSQLSchemaManager::class, // Separate by schema instead of database
|
// 'pgsql' => Stancl\Tenancy\Database\TenantDatabaseManagers\PostgreSQLSchemaManager::class, // Separate by schema instead of database
|
||||||
],
|
],
|
||||||
],
|
],
|
||||||
|
|
||||||
|
|
@ -118,6 +119,24 @@ return [
|
||||||
'public' => '%storage_path%/app/public/',
|
'public' => '%storage_path%/app/public/',
|
||||||
],
|
],
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Tenant-aware Storage::disk()->url() can be enabled for specific local disks here
|
||||||
|
* by mapping the disk's name to a name with '%tenant_id%' (this will be used as the public name of the disk).
|
||||||
|
* Doing that will override the disk's default URL with a URL containing the current tenant's key.
|
||||||
|
*
|
||||||
|
* For example, Storage::disk('public')->url('') will return https://your-app.test/storage/ by default.
|
||||||
|
* After adding 'public' => 'public-%tenant_id%' to 'url_override',
|
||||||
|
* the returned URL will be https://your-app.test/public-1/ (%tenant_id% gets substitued by the current tenant's ID).
|
||||||
|
*
|
||||||
|
* Use `php artisan tenants:link` to create a symbolic link from the tenant's storage to its public directory.
|
||||||
|
*/
|
||||||
|
'url_override' => [
|
||||||
|
// Note that the local disk you add must exist in the tenancy.filesystem.root_override config
|
||||||
|
// todo@v4 Rename %tenant_id% to %tenant_key%
|
||||||
|
// todo@v4 Rename url_override to something that describes the config key better
|
||||||
|
'public' => 'public-%tenant_id%',
|
||||||
|
],
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Should storage_path() be suffixed.
|
* Should storage_path() be suffixed.
|
||||||
*
|
*
|
||||||
|
|
|
||||||
|
|
@ -18,10 +18,10 @@
|
||||||
"php": "^8.1",
|
"php": "^8.1",
|
||||||
"ext-json": "*",
|
"ext-json": "*",
|
||||||
"illuminate/support": "^9.0",
|
"illuminate/support": "^9.0",
|
||||||
"facade/ignition-contracts": "^1.0",
|
"spatie/ignition": "^1.4",
|
||||||
"ramsey/uuid": "^4.0",
|
"ramsey/uuid": "^4.0",
|
||||||
"stancl/jobpipeline": "^1.6",
|
"stancl/jobpipeline": "^1.0",
|
||||||
"stancl/virtualcolumn": "^1.2"
|
"stancl/virtualcolumn": "^1.0"
|
||||||
},
|
},
|
||||||
"require-dev": {
|
"require-dev": {
|
||||||
"laravel/framework": "^9.0",
|
"laravel/framework": "^9.0",
|
||||||
|
|
@ -29,7 +29,8 @@
|
||||||
"league/flysystem-aws-s3-v3": "^3.0",
|
"league/flysystem-aws-s3-v3": "^3.0",
|
||||||
"doctrine/dbal": "^2.10",
|
"doctrine/dbal": "^2.10",
|
||||||
"spatie/valuestore": "^1.2.5",
|
"spatie/valuestore": "^1.2.5",
|
||||||
"pestphp/pest": "^1.21"
|
"pestphp/pest": "^1.21",
|
||||||
|
"nunomaduro/larastan": "^1.0"
|
||||||
},
|
},
|
||||||
"autoload": {
|
"autoload": {
|
||||||
"psr-4": {
|
"psr-4": {
|
||||||
|
|
@ -60,7 +61,10 @@
|
||||||
"docker-down": "PHP_VERSION=8.1 docker-compose down",
|
"docker-down": "PHP_VERSION=8.1 docker-compose down",
|
||||||
"docker-rebuild": "PHP_VERSION=8.1 docker-compose up -d --no-deps --build",
|
"docker-rebuild": "PHP_VERSION=8.1 docker-compose up -d --no-deps --build",
|
||||||
"docker-m1": "ln -s docker-compose-m1.override.yml docker-compose.override.yml",
|
"docker-m1": "ln -s docker-compose-m1.override.yml docker-compose.override.yml",
|
||||||
"test": "PHP_VERSION=8.1 ./test"
|
"coverage": "open coverage/phpunit/html/index.html",
|
||||||
|
"phpstan": "vendor/bin/phpstan",
|
||||||
|
"test": "PHP_VERSION=8.1 ./test --no-coverage",
|
||||||
|
"test-full": "PHP_VERSION=8.1 ./test"
|
||||||
},
|
},
|
||||||
"minimum-stability": "dev",
|
"minimum-stability": "dev",
|
||||||
"prefer-stable": true,
|
"prefer-stable": true,
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,8 @@ services:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
redis:
|
redis:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
|
# mssql:
|
||||||
|
# condition: service_healthy
|
||||||
volumes:
|
volumes:
|
||||||
- .:/var/www/html:delegated
|
- .:/var/www/html:delegated
|
||||||
environment:
|
environment:
|
||||||
|
|
@ -74,4 +76,8 @@ services:
|
||||||
environment:
|
environment:
|
||||||
- ACCEPT_EULA=Y
|
- ACCEPT_EULA=Y
|
||||||
- SA_PASSWORD=P@ssword # todo reuse values from env above
|
- SA_PASSWORD=P@ssword # todo reuse values from env above
|
||||||
# todo missing health check
|
healthcheck:
|
||||||
|
test: /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P P@ssword -Q "SELECT 1" -b -o /dev/null
|
||||||
|
interval: 10s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 10
|
||||||
|
|
|
||||||
34
phpstan.neon
Normal file
34
phpstan.neon
Normal file
|
|
@ -0,0 +1,34 @@
|
||||||
|
includes:
|
||||||
|
- ./vendor/nunomaduro/larastan/extension.neon
|
||||||
|
|
||||||
|
parameters:
|
||||||
|
paths:
|
||||||
|
- src
|
||||||
|
# - tests
|
||||||
|
|
||||||
|
level: 8
|
||||||
|
|
||||||
|
universalObjectCratesClasses:
|
||||||
|
- Illuminate\Routing\Route
|
||||||
|
- Illuminate\Database\Eloquent\Model
|
||||||
|
|
||||||
|
ignoreErrors:
|
||||||
|
-
|
||||||
|
message: '#Cannot access offset (.*?) on Illuminate\\Contracts\\Foundation\\Application#'
|
||||||
|
paths:
|
||||||
|
- src/TenancyServiceProvider.php
|
||||||
|
-
|
||||||
|
message: '#invalid type Laravel\\Telescope\\IncomingEntry#'
|
||||||
|
paths:
|
||||||
|
- src/Features/TelescopeTags.php
|
||||||
|
-
|
||||||
|
message: '#Parameter \#1 \$key of method Illuminate\\Contracts\\Cache\\Repository::put\(\) expects string#'
|
||||||
|
paths:
|
||||||
|
- src/helpers.php
|
||||||
|
-
|
||||||
|
message: '#PHPDoc tag \@param has invalid value \(dynamic#'
|
||||||
|
paths:
|
||||||
|
- src/helpers.php
|
||||||
|
|
||||||
|
checkMissingIterableValueType: false
|
||||||
|
treatPhpDocTypesAsCertain: false
|
||||||
55
src/Actions/CreateStorageSymlinksAction.php
Normal file
55
src/Actions/CreateStorageSymlinksAction.php
Normal file
|
|
@ -0,0 +1,55 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Stancl\Tenancy\Actions;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
use Illuminate\Support\LazyCollection;
|
||||||
|
use Stancl\Tenancy\Concerns\DealsWithTenantSymlinks;
|
||||||
|
use Stancl\Tenancy\Contracts\Tenant;
|
||||||
|
use Stancl\Tenancy\Events\CreatingStorageSymlink;
|
||||||
|
use Stancl\Tenancy\Events\StorageSymlinkCreated;
|
||||||
|
|
||||||
|
class CreateStorageSymlinksAction
|
||||||
|
{
|
||||||
|
use DealsWithTenantSymlinks;
|
||||||
|
|
||||||
|
public static function handle(Tenant|Collection|LazyCollection $tenants, bool $relativeLink = false, bool $force = false): void
|
||||||
|
{
|
||||||
|
$tenants = $tenants instanceof Tenant ? collect([$tenants]) : $tenants;
|
||||||
|
|
||||||
|
/** @var Tenant $tenant */
|
||||||
|
foreach ($tenants as $tenant) {
|
||||||
|
foreach (static::possibleTenantSymlinks($tenant) as $publicPath => $storagePath) {
|
||||||
|
static::createLink($publicPath, $storagePath, $tenant, $relativeLink, $force);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected static function createLink(string $publicPath, string $storagePath, Tenant $tenant, bool $relativeLink, bool $force): void
|
||||||
|
{
|
||||||
|
event(new CreatingStorageSymlink($tenant));
|
||||||
|
|
||||||
|
if (static::symlinkExists($publicPath)) {
|
||||||
|
// If $force isn't passed, don't overwrite the existing symlink
|
||||||
|
throw_if(! $force, new Exception("The [$publicPath] link already exists."));
|
||||||
|
|
||||||
|
app()->make('files')->delete($publicPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make sure the storage path exists before we create a symlink
|
||||||
|
if (! is_dir($storagePath)) {
|
||||||
|
mkdir($storagePath, 0777, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($relativeLink) {
|
||||||
|
app()->make('files')->relativeLink($storagePath, $publicPath);
|
||||||
|
} else {
|
||||||
|
app()->make('files')->link($storagePath, $publicPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
event((new StorageSymlinkCreated($tenant)));
|
||||||
|
}
|
||||||
|
}
|
||||||
40
src/Actions/RemoveStorageSymlinksAction.php
Normal file
40
src/Actions/RemoveStorageSymlinksAction.php
Normal file
|
|
@ -0,0 +1,40 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Stancl\Tenancy\Actions;
|
||||||
|
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
use Illuminate\Support\LazyCollection;
|
||||||
|
use Stancl\Tenancy\Concerns\DealsWithTenantSymlinks;
|
||||||
|
use Stancl\Tenancy\Contracts\Tenant;
|
||||||
|
use Stancl\Tenancy\Events\RemovingStorageSymlink;
|
||||||
|
use Stancl\Tenancy\Events\StorageSymlinkRemoved;
|
||||||
|
|
||||||
|
class RemoveStorageSymlinksAction
|
||||||
|
{
|
||||||
|
use DealsWithTenantSymlinks;
|
||||||
|
|
||||||
|
public static function handle(Tenant|Collection|LazyCollection $tenants): void
|
||||||
|
{
|
||||||
|
$tenants = $tenants instanceof Tenant ? collect([$tenants]) : $tenants;
|
||||||
|
|
||||||
|
/** @var Tenant $tenant */
|
||||||
|
foreach ($tenants as $tenant) {
|
||||||
|
foreach (static::possibleTenantSymlinks($tenant) as $publicPath => $storagePath) {
|
||||||
|
static::removeLink($publicPath, $tenant);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected static function removeLink(string $publicPath, Tenant $tenant): void
|
||||||
|
{
|
||||||
|
if (static::symlinkExists($publicPath)) {
|
||||||
|
event(new RemovingStorageSymlink($tenant));
|
||||||
|
|
||||||
|
app()->make('files')->delete($publicPath);
|
||||||
|
|
||||||
|
event(new StorageSymlinkRemoved($tenant));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
41
src/Bootstrappers/BatchTenancyBootstrapper.php
Normal file
41
src/Bootstrappers/BatchTenancyBootstrapper.php
Normal file
|
|
@ -0,0 +1,41 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Stancl\Tenancy\Bootstrappers;
|
||||||
|
|
||||||
|
use Illuminate\Bus\DatabaseBatchRepository;
|
||||||
|
use Illuminate\Database\Connection;
|
||||||
|
use Illuminate\Database\DatabaseManager;
|
||||||
|
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
|
||||||
|
use Stancl\Tenancy\Contracts\Tenant;
|
||||||
|
|
||||||
|
class BatchTenancyBootstrapper implements TenancyBootstrapper
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* The previous database connection instance.
|
||||||
|
*/
|
||||||
|
protected ?Connection $previousConnection = null;
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
protected DatabaseBatchRepository $batchRepository,
|
||||||
|
protected DatabaseManager $databaseManager
|
||||||
|
) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public function bootstrap(Tenant $tenant)
|
||||||
|
{
|
||||||
|
// Update batch repository connection to use the tenant connection
|
||||||
|
$this->previousConnection = $this->batchRepository->getConnection();
|
||||||
|
$this->batchRepository->setConnection($this->databaseManager->connection('tenant'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function revert()
|
||||||
|
{
|
||||||
|
if ($this->previousConnection) {
|
||||||
|
// Replace batch repository connection with the previously replaced one
|
||||||
|
$this->batchRepository->setConnection($this->previousConnection);
|
||||||
|
$this->previousConnection = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -6,7 +6,7 @@ namespace Stancl\Tenancy\Bootstrappers;
|
||||||
|
|
||||||
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
|
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
|
||||||
use Stancl\Tenancy\Contracts\Tenant;
|
use Stancl\Tenancy\Contracts\Tenant;
|
||||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||||
use Stancl\Tenancy\Database\DatabaseManager;
|
use Stancl\Tenancy\Database\DatabaseManager;
|
||||||
use Stancl\Tenancy\Exceptions\TenantDatabaseDoesNotExistException;
|
use Stancl\Tenancy\Exceptions\TenantDatabaseDoesNotExistException;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -57,9 +57,10 @@ class FilesystemTenancyBootstrapper implements TenancyBootstrapper
|
||||||
|
|
||||||
foreach ($this->app['config']['tenancy.filesystem.disks'] as $disk) {
|
foreach ($this->app['config']['tenancy.filesystem.disks'] as $disk) {
|
||||||
// todo@v4 \League\Flysystem\PathPrefixer is making this a lot more painful in flysystem v2
|
// todo@v4 \League\Flysystem\PathPrefixer is making this a lot more painful in flysystem v2
|
||||||
|
$diskConfig = $this->app['config']["filesystems.disks.{$disk}"];
|
||||||
|
$originalRoot = $diskConfig['root'] ?? null;
|
||||||
|
|
||||||
$originalRoot = $this->app['config']["filesystems.disks.{$disk}.root"];
|
$this->originalPaths['disks']['path'][$disk] = $originalRoot;
|
||||||
$this->originalPaths['disks'][$disk] = $originalRoot;
|
|
||||||
|
|
||||||
$finalPrefix = str_replace(
|
$finalPrefix = str_replace(
|
||||||
['%storage_path%', '%tenant%'],
|
['%storage_path%', '%tenant%'],
|
||||||
|
|
@ -74,6 +75,19 @@ class FilesystemTenancyBootstrapper implements TenancyBootstrapper
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->app['config']["filesystems.disks.{$disk}.root"] = $finalPrefix;
|
$this->app['config']["filesystems.disks.{$disk}.root"] = $finalPrefix;
|
||||||
|
|
||||||
|
// Storage Url
|
||||||
|
if ($diskConfig['driver'] === 'local') {
|
||||||
|
$this->originalPaths['disks']['url'][$disk] = $diskConfig['url'] ?? null;
|
||||||
|
|
||||||
|
if ($url = str_replace(
|
||||||
|
'%tenant_id%',
|
||||||
|
$tenant->getTenantKey(),
|
||||||
|
$this->app['config']["tenancy.filesystem.url_override.{$disk}"] ?? ''
|
||||||
|
)) {
|
||||||
|
$this->app['config']["filesystems.disks.{$disk}.url"] = url($url);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -88,8 +102,16 @@ class FilesystemTenancyBootstrapper implements TenancyBootstrapper
|
||||||
|
|
||||||
// Storage facade
|
// Storage facade
|
||||||
Storage::forgetDisk($this->app['config']['tenancy.filesystem.disks']);
|
Storage::forgetDisk($this->app['config']['tenancy.filesystem.disks']);
|
||||||
foreach ($this->app['config']['tenancy.filesystem.disks'] as $disk) {
|
foreach ($this->app['config']['tenancy.filesystem.disks'] as $diskName) {
|
||||||
$this->app['config']["filesystems.disks.{$disk}.root"] = $this->originalPaths['disks'][$disk];
|
$this->app['config']["filesystems.disks.$diskName.root"] = $this->originalPaths['disks']['path'][$diskName];
|
||||||
|
$diskConfig = $this->app['config']['filesystems.disks.' . $diskName];
|
||||||
|
|
||||||
|
// Storage Url
|
||||||
|
$url = $this->originalPaths['disks.url.' . $diskName] ?? null;
|
||||||
|
|
||||||
|
if ($diskConfig['driver'] === 'local' && ! is_null($url)) {
|
||||||
|
$$this->app['config']["filesystems.disks.$diskName.url"] = $url;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
42
src/Bootstrappers/Integrations/ScoutTenancyBootstrapper.php
Normal file
42
src/Bootstrappers/Integrations/ScoutTenancyBootstrapper.php
Normal file
|
|
@ -0,0 +1,42 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Stancl\Tenancy\Bootstrappers\Integrations;
|
||||||
|
|
||||||
|
use Illuminate\Contracts\Config\Repository;
|
||||||
|
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
|
||||||
|
use Stancl\Tenancy\Contracts\Tenant;
|
||||||
|
|
||||||
|
class ScoutTenancyBootstrapper implements TenancyBootstrapper
|
||||||
|
{
|
||||||
|
/** @var Repository */
|
||||||
|
protected $config;
|
||||||
|
|
||||||
|
/** @var string */
|
||||||
|
protected $originalScoutPrefix;
|
||||||
|
|
||||||
|
public function __construct(Repository $config)
|
||||||
|
{
|
||||||
|
$this->config = $config;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function bootstrap(Tenant $tenant)
|
||||||
|
{
|
||||||
|
if (! isset($this->originalScoutPrefix)) {
|
||||||
|
$this->originalScoutPrefix = $this->config->get('scout.prefix');
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->config->set('scout.prefix', $this->getTenantPrefix($tenant));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function revert()
|
||||||
|
{
|
||||||
|
$this->config->set('scout.prefix', $this->originalScoutPrefix);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function getTenantPrefix(Tenant $tenant): string
|
||||||
|
{
|
||||||
|
return (string) $tenant->getTenantKey();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -6,6 +6,8 @@ namespace Stancl\Tenancy;
|
||||||
|
|
||||||
use Illuminate\Cache\CacheManager as BaseCacheManager;
|
use Illuminate\Cache\CacheManager as BaseCacheManager;
|
||||||
|
|
||||||
|
// todo move to Cache namespace?
|
||||||
|
|
||||||
class CacheManager extends BaseCacheManager
|
class CacheManager extends BaseCacheManager
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
|
|
@ -26,7 +28,7 @@ class CacheManager extends BaseCacheManager
|
||||||
}
|
}
|
||||||
|
|
||||||
$names = $parameters[0];
|
$names = $parameters[0];
|
||||||
$names = (array) $names; // cache()->tags('foo') https://laravel.com/docs/5.7/cache#removing-tagged-cache-items
|
$names = (array) $names; // cache()->tags('foo') https://laravel.com/docs/9.x/cache#removing-tagged-cache-items
|
||||||
|
|
||||||
return $this->store()->tags(array_merge($tags, $names));
|
return $this->store()->tags(array_merge($tags, $names));
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -8,24 +8,11 @@ use Illuminate\Console\Command;
|
||||||
|
|
||||||
class Install extends Command
|
class Install extends Command
|
||||||
{
|
{
|
||||||
/**
|
|
||||||
* The name and signature of the console command.
|
|
||||||
*
|
|
||||||
* @var string
|
|
||||||
*/
|
|
||||||
protected $signature = 'tenancy:install';
|
protected $signature = 'tenancy:install';
|
||||||
|
|
||||||
/**
|
|
||||||
* The console command description.
|
|
||||||
*
|
|
||||||
* @var string
|
|
||||||
*/
|
|
||||||
protected $description = 'Install stancl/tenancy.';
|
protected $description = 'Install stancl/tenancy.';
|
||||||
|
|
||||||
/**
|
public function handle(): void
|
||||||
* Execute the console command.
|
|
||||||
*/
|
|
||||||
public function handle()
|
|
||||||
{
|
{
|
||||||
$this->comment('Installing stancl/tenancy...');
|
$this->comment('Installing stancl/tenancy...');
|
||||||
$this->callSilent('vendor:publish', [
|
$this->callSilent('vendor:publish', [
|
||||||
|
|
|
||||||
58
src/Commands/Link.php
Normal file
58
src/Commands/Link.php
Normal file
|
|
@ -0,0 +1,58 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Stancl\Tenancy\Commands;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
|
use Illuminate\Console\Command;
|
||||||
|
use Illuminate\Support\LazyCollection;
|
||||||
|
use Stancl\Tenancy\Actions\CreateStorageSymlinksAction;
|
||||||
|
use Stancl\Tenancy\Actions\RemoveStorageSymlinksAction;
|
||||||
|
use Stancl\Tenancy\Concerns\HasATenantsOption;
|
||||||
|
|
||||||
|
class Link extends Command
|
||||||
|
{
|
||||||
|
use HasATenantsOption;
|
||||||
|
|
||||||
|
protected $signature = 'tenants:link
|
||||||
|
{--tenants=* : The tenant(s) to run the command for. Default: all}
|
||||||
|
{--relative : Create the symbolic link using relative paths}
|
||||||
|
{--force : Recreate existing symbolic links}
|
||||||
|
{--remove : Remove symbolic links}';
|
||||||
|
|
||||||
|
protected $description = 'Create or remove tenant symbolic links.';
|
||||||
|
|
||||||
|
public function handle(): void
|
||||||
|
{
|
||||||
|
$tenants = $this->getTenants();
|
||||||
|
|
||||||
|
try {
|
||||||
|
if ($this->option('remove')) {
|
||||||
|
$this->removeLinks($tenants);
|
||||||
|
} else {
|
||||||
|
$this->createLinks($tenants);
|
||||||
|
}
|
||||||
|
} catch (Exception $exception) {
|
||||||
|
$this->error($exception->getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function removeLinks(LazyCollection $tenants): void
|
||||||
|
{
|
||||||
|
RemoveStorageSymlinksAction::handle($tenants);
|
||||||
|
|
||||||
|
$this->info('The links have been removed.');
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function createLinks(LazyCollection $tenants): void
|
||||||
|
{
|
||||||
|
CreateStorageSymlinksAction::handle(
|
||||||
|
$tenants,
|
||||||
|
$this->option('relative') ?? false,
|
||||||
|
$this->option('force') ?? false,
|
||||||
|
);
|
||||||
|
|
||||||
|
$this->info('The links have been created.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -7,7 +7,6 @@ namespace Stancl\Tenancy\Commands;
|
||||||
use Illuminate\Contracts\Events\Dispatcher;
|
use Illuminate\Contracts\Events\Dispatcher;
|
||||||
use Illuminate\Database\Console\Migrations\MigrateCommand;
|
use Illuminate\Database\Console\Migrations\MigrateCommand;
|
||||||
use Illuminate\Database\Migrations\Migrator;
|
use Illuminate\Database\Migrations\Migrator;
|
||||||
use Stancl\Tenancy\Concerns\DealsWithMigrations;
|
|
||||||
use Stancl\Tenancy\Concerns\ExtendsLaravelCommand;
|
use Stancl\Tenancy\Concerns\ExtendsLaravelCommand;
|
||||||
use Stancl\Tenancy\Concerns\HasATenantsOption;
|
use Stancl\Tenancy\Concerns\HasATenantsOption;
|
||||||
use Stancl\Tenancy\Events\DatabaseMigrated;
|
use Stancl\Tenancy\Events\DatabaseMigrated;
|
||||||
|
|
@ -15,7 +14,7 @@ use Stancl\Tenancy\Events\MigratingDatabase;
|
||||||
|
|
||||||
class Migrate extends MigrateCommand
|
class Migrate extends MigrateCommand
|
||||||
{
|
{
|
||||||
use HasATenantsOption, DealsWithMigrations, ExtendsLaravelCommand;
|
use HasATenantsOption, ExtendsLaravelCommand;
|
||||||
|
|
||||||
protected $description = 'Run migrations for tenant(s)';
|
protected $description = 'Run migrations for tenant(s)';
|
||||||
|
|
||||||
|
|
@ -31,10 +30,7 @@ class Migrate extends MigrateCommand
|
||||||
$this->specifyParameters();
|
$this->specifyParameters();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
public function handle(): int
|
||||||
* Execute the console command.
|
|
||||||
*/
|
|
||||||
public function handle()
|
|
||||||
{
|
{
|
||||||
foreach (config('tenancy.migration_parameters') as $parameter => $value) {
|
foreach (config('tenancy.migration_parameters') as $parameter => $value) {
|
||||||
if (! $this->input->hasParameterOption($parameter)) {
|
if (! $this->input->hasParameterOption($parameter)) {
|
||||||
|
|
@ -43,10 +39,10 @@ class Migrate extends MigrateCommand
|
||||||
}
|
}
|
||||||
|
|
||||||
if (! $this->confirmToProceed()) {
|
if (! $this->confirmToProceed()) {
|
||||||
return;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
|
tenancy()->runForMultiple($this->getTenants(), function ($tenant) {
|
||||||
$this->line("Tenant: {$tenant->getTenantKey()}");
|
$this->line("Tenant: {$tenant->getTenantKey()}");
|
||||||
|
|
||||||
event(new MigratingDatabase($tenant));
|
event(new MigratingDatabase($tenant));
|
||||||
|
|
@ -56,5 +52,7 @@ class Migrate extends MigrateCommand
|
||||||
|
|
||||||
event(new DatabaseMigrated($tenant));
|
event(new DatabaseMigrated($tenant));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,19 +5,13 @@ declare(strict_types=1);
|
||||||
namespace Stancl\Tenancy\Commands;
|
namespace Stancl\Tenancy\Commands;
|
||||||
|
|
||||||
use Illuminate\Console\Command;
|
use Illuminate\Console\Command;
|
||||||
use Stancl\Tenancy\Concerns\DealsWithMigrations;
|
|
||||||
use Stancl\Tenancy\Concerns\HasATenantsOption;
|
use Stancl\Tenancy\Concerns\HasATenantsOption;
|
||||||
use Symfony\Component\Console\Input\InputOption;
|
use Symfony\Component\Console\Input\InputOption;
|
||||||
|
|
||||||
final class MigrateFresh extends Command
|
final class MigrateFresh extends Command
|
||||||
{
|
{
|
||||||
use HasATenantsOption, DealsWithMigrations;
|
use HasATenantsOption;
|
||||||
|
|
||||||
/**
|
|
||||||
* The console command description.
|
|
||||||
*
|
|
||||||
* @var string
|
|
||||||
*/
|
|
||||||
protected $description = 'Drop all tables and re-run all migrations for tenant(s)';
|
protected $description = 'Drop all tables and re-run all migrations for tenant(s)';
|
||||||
|
|
||||||
public function __construct()
|
public function __construct()
|
||||||
|
|
@ -29,12 +23,9 @@ final class MigrateFresh extends Command
|
||||||
$this->setName('tenants:migrate-fresh');
|
$this->setName('tenants:migrate-fresh');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
public function handle(): void
|
||||||
* Execute the console command.
|
|
||||||
*/
|
|
||||||
public function handle()
|
|
||||||
{
|
{
|
||||||
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
|
tenancy()->runForMultiple($this->getTenants(), function ($tenant) {
|
||||||
$this->info('Dropping tables.');
|
$this->info('Dropping tables.');
|
||||||
$this->call('db:wipe', array_filter([
|
$this->call('db:wipe', array_filter([
|
||||||
'--database' => 'tenant',
|
'--database' => 'tenant',
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,6 @@ namespace Stancl\Tenancy\Commands;
|
||||||
|
|
||||||
use Illuminate\Database\Console\Migrations\RollbackCommand;
|
use Illuminate\Database\Console\Migrations\RollbackCommand;
|
||||||
use Illuminate\Database\Migrations\Migrator;
|
use Illuminate\Database\Migrations\Migrator;
|
||||||
use Stancl\Tenancy\Concerns\DealsWithMigrations;
|
|
||||||
use Stancl\Tenancy\Concerns\ExtendsLaravelCommand;
|
use Stancl\Tenancy\Concerns\ExtendsLaravelCommand;
|
||||||
use Stancl\Tenancy\Concerns\HasATenantsOption;
|
use Stancl\Tenancy\Concerns\HasATenantsOption;
|
||||||
use Stancl\Tenancy\Events\DatabaseRolledBack;
|
use Stancl\Tenancy\Events\DatabaseRolledBack;
|
||||||
|
|
@ -14,25 +13,10 @@ use Stancl\Tenancy\Events\RollingBackDatabase;
|
||||||
|
|
||||||
class Rollback extends RollbackCommand
|
class Rollback extends RollbackCommand
|
||||||
{
|
{
|
||||||
use HasATenantsOption, DealsWithMigrations, ExtendsLaravelCommand;
|
use HasATenantsOption, ExtendsLaravelCommand;
|
||||||
|
|
||||||
protected static function getTenantCommandName(): string
|
|
||||||
{
|
|
||||||
return 'tenants:rollback';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The console command description.
|
|
||||||
*
|
|
||||||
* @var string
|
|
||||||
*/
|
|
||||||
protected $description = 'Rollback migrations for tenant(s).';
|
protected $description = 'Rollback migrations for tenant(s).';
|
||||||
|
|
||||||
/**
|
|
||||||
* Create a new command instance.
|
|
||||||
*
|
|
||||||
* @return void
|
|
||||||
*/
|
|
||||||
public function __construct(Migrator $migrator)
|
public function __construct(Migrator $migrator)
|
||||||
{
|
{
|
||||||
parent::__construct($migrator);
|
parent::__construct($migrator);
|
||||||
|
|
@ -40,10 +24,7 @@ class Rollback extends RollbackCommand
|
||||||
$this->specifyTenantSignature();
|
$this->specifyTenantSignature();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
public function handle(): int
|
||||||
* Execute the console command.
|
|
||||||
*/
|
|
||||||
public function handle()
|
|
||||||
{
|
{
|
||||||
foreach (config('tenancy.migration_parameters') as $parameter => $value) {
|
foreach (config('tenancy.migration_parameters') as $parameter => $value) {
|
||||||
if (! $this->input->hasParameterOption($parameter)) {
|
if (! $this->input->hasParameterOption($parameter)) {
|
||||||
|
|
@ -52,7 +33,7 @@ class Rollback extends RollbackCommand
|
||||||
}
|
}
|
||||||
|
|
||||||
if (! $this->confirmToProceed()) {
|
if (! $this->confirmToProceed()) {
|
||||||
return;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
|
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
|
||||||
|
|
@ -65,5 +46,12 @@ class Rollback extends RollbackCommand
|
||||||
|
|
||||||
event(new DatabaseRolledBack($tenant));
|
event(new DatabaseRolledBack($tenant));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected static function getTenantCommandName(): string
|
||||||
|
{
|
||||||
|
return 'tenants:rollback';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,51 +5,37 @@ declare(strict_types=1);
|
||||||
namespace Stancl\Tenancy\Commands;
|
namespace Stancl\Tenancy\Commands;
|
||||||
|
|
||||||
use Illuminate\Console\Command;
|
use Illuminate\Console\Command;
|
||||||
|
use Illuminate\Contracts\Console\Kernel;
|
||||||
|
use Symfony\Component\Console\Input\ArgvInput;
|
||||||
|
use Symfony\Component\Console\Output\ConsoleOutput;
|
||||||
|
|
||||||
class Run extends Command
|
class Run extends Command
|
||||||
{
|
{
|
||||||
/**
|
|
||||||
* The console command description.
|
|
||||||
*
|
|
||||||
* @var string
|
|
||||||
*/
|
|
||||||
protected $description = 'Run a command for tenant(s)';
|
protected $description = 'Run a command for tenant(s)';
|
||||||
|
|
||||||
/**
|
protected $signature = 'tenants:run {commandname : The artisan command.}
|
||||||
* The name and signature of the console command.
|
{--tenants=* : The tenant(s) to run the command for. Default: all}';
|
||||||
*
|
|
||||||
* @var string
|
|
||||||
*/
|
|
||||||
protected $signature = "tenants:run {commandname : The command's name.}
|
|
||||||
{--tenants=* : The tenant(s) to run the command for. Default: all}
|
|
||||||
{--argument=* : The arguments to pass to the command. Default: none}
|
|
||||||
{--option=* : The options to pass to the command. Default: none}";
|
|
||||||
|
|
||||||
/**
|
public function handle(): void
|
||||||
* Execute the console command.
|
|
||||||
*/
|
|
||||||
public function handle()
|
|
||||||
{
|
{
|
||||||
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
|
$argvInput = $this->argvInput();
|
||||||
|
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) use ($argvInput) {
|
||||||
$this->line("Tenant: {$tenant->getTenantKey()}");
|
$this->line("Tenant: {$tenant->getTenantKey()}");
|
||||||
|
|
||||||
$callback = function ($prefix = '') {
|
$this->getLaravel()
|
||||||
return function ($arguments, $argument) use ($prefix) {
|
->make(Kernel::class)
|
||||||
[$key, $value] = explode('=', $argument, 2);
|
->handle($argvInput, new ConsoleOutput);
|
||||||
$arguments[$prefix . $key] = $value;
|
|
||||||
|
|
||||||
return $arguments;
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
// Turns ['foo=bar', 'abc=xyz=zzz'] into ['foo' => 'bar', 'abc' => 'xyz=zzz']
|
|
||||||
$arguments = array_reduce($this->option('argument'), $callback(), []);
|
|
||||||
|
|
||||||
// Turns ['foo=bar', 'abc=xyz=zzz'] into ['--foo' => 'bar', '--abc' => 'xyz=zzz']
|
|
||||||
$options = array_reduce($this->option('option'), $callback('--'), []);
|
|
||||||
|
|
||||||
// Run command
|
|
||||||
$this->call($this->argument('commandname'), array_merge($arguments, $options));
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected function argvInput(): ArgvInput
|
||||||
|
{
|
||||||
|
// Convert string command to array
|
||||||
|
$subCommand = explode(' ', $this->argument('commandname'));
|
||||||
|
|
||||||
|
// Add "artisan" as first parameter because ArgvInput expects "artisan" as first parameter and later removes it
|
||||||
|
array_unshift($subCommand, 'artisan');
|
||||||
|
|
||||||
|
return new ArgvInput($subCommand);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -14,29 +14,16 @@ class Seed extends SeedCommand
|
||||||
{
|
{
|
||||||
use HasATenantsOption;
|
use HasATenantsOption;
|
||||||
|
|
||||||
/**
|
|
||||||
* The console command description.
|
|
||||||
*
|
|
||||||
* @var string
|
|
||||||
*/
|
|
||||||
protected $description = 'Seed tenant database(s).';
|
protected $description = 'Seed tenant database(s).';
|
||||||
|
|
||||||
protected $name = 'tenants:seed';
|
protected $name = 'tenants:seed';
|
||||||
|
|
||||||
/**
|
|
||||||
* Create a new command instance.
|
|
||||||
*
|
|
||||||
* @return void
|
|
||||||
*/
|
|
||||||
public function __construct(ConnectionResolverInterface $resolver)
|
public function __construct(ConnectionResolverInterface $resolver)
|
||||||
{
|
{
|
||||||
parent::__construct($resolver);
|
parent::__construct($resolver);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
public function handle(): int
|
||||||
* Execute the console command.
|
|
||||||
*/
|
|
||||||
public function handle()
|
|
||||||
{
|
{
|
||||||
foreach (config('tenancy.seeder_parameters') as $parameter => $value) {
|
foreach (config('tenancy.seeder_parameters') as $parameter => $value) {
|
||||||
if (! $this->input->hasParameterOption($parameter)) {
|
if (! $this->input->hasParameterOption($parameter)) {
|
||||||
|
|
@ -45,7 +32,7 @@ class Seed extends SeedCommand
|
||||||
}
|
}
|
||||||
|
|
||||||
if (! $this->confirmToProceed()) {
|
if (! $this->confirmToProceed()) {
|
||||||
return;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
|
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
|
||||||
|
|
@ -58,5 +45,7 @@ class Seed extends SeedCommand
|
||||||
|
|
||||||
event(new DatabaseSeeded($tenant));
|
event(new DatabaseSeeded($tenant));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -9,24 +9,11 @@ use Stancl\Tenancy\Contracts\Tenant;
|
||||||
|
|
||||||
class TenantList extends Command
|
class TenantList extends Command
|
||||||
{
|
{
|
||||||
/**
|
|
||||||
* The name and signature of the console command.
|
|
||||||
*
|
|
||||||
* @var string
|
|
||||||
*/
|
|
||||||
protected $signature = 'tenants:list';
|
protected $signature = 'tenants:list';
|
||||||
|
|
||||||
/**
|
|
||||||
* The console command description.
|
|
||||||
*
|
|
||||||
* @var string
|
|
||||||
*/
|
|
||||||
protected $description = 'List tenants.';
|
protected $description = 'List tenants.';
|
||||||
|
|
||||||
/**
|
public function handle(): void
|
||||||
* Execute the console command.
|
|
||||||
*/
|
|
||||||
public function handle()
|
|
||||||
{
|
{
|
||||||
$this->info('Listing all tenants.');
|
$this->info('Listing all tenants.');
|
||||||
tenancy()
|
tenancy()
|
||||||
|
|
|
||||||
|
|
@ -6,12 +6,12 @@ namespace Stancl\Tenancy\Concerns;
|
||||||
|
|
||||||
trait DealsWithMigrations
|
trait DealsWithMigrations
|
||||||
{
|
{
|
||||||
protected function getMigrationPaths()
|
protected function getMigrationPaths(): array
|
||||||
{
|
{
|
||||||
if ($this->input->hasOption('path') && $this->input->getOption('path')) {
|
if ($this->input->hasOption('path') && $this->input->getOption('path')) {
|
||||||
return parent::getMigrationPaths();
|
return parent::getMigrationPaths();
|
||||||
}
|
}
|
||||||
|
|
||||||
return database_path('migrations/tenant');
|
return [database_path('migrations/tenant')];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
46
src/Concerns/DealsWithTenantSymlinks.php
Normal file
46
src/Concerns/DealsWithTenantSymlinks.php
Normal file
|
|
@ -0,0 +1,46 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Stancl\Tenancy\Concerns;
|
||||||
|
|
||||||
|
use Illuminate\Support\Collection;
|
||||||
|
use Stancl\Tenancy\Database\Models\Tenant;
|
||||||
|
|
||||||
|
trait DealsWithTenantSymlinks
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Get all possible tenant symlinks, existing or not (array of ['public path' => 'storage path']).
|
||||||
|
*
|
||||||
|
* Tenants can have a symlink for each disk registered in the tenancy.filesystem.url_override config.
|
||||||
|
*
|
||||||
|
* This is used for creating all possible tenant symlinks and removing all existing tenant symlinks.
|
||||||
|
*
|
||||||
|
* @return Collection<string, string>
|
||||||
|
*/
|
||||||
|
protected static function possibleTenantSymlinks(Tenant $tenant): Collection
|
||||||
|
{
|
||||||
|
$diskUrls = config('tenancy.filesystem.url_override');
|
||||||
|
$disks = config('tenancy.filesystem.root_override');
|
||||||
|
$suffixBase = config('tenancy.filesystem.suffix_base');
|
||||||
|
$symlinks = collect();
|
||||||
|
$tenantKey = $tenant->getTenantKey();
|
||||||
|
|
||||||
|
foreach ($diskUrls as $disk => $publicPath) {
|
||||||
|
$storagePath = str_replace('%storage_path%', $suffixBase . $tenantKey, $disks[$disk]);
|
||||||
|
$publicPath = str_replace('%tenant_id%', $tenantKey, $publicPath);
|
||||||
|
|
||||||
|
tenancy()->central(function () use ($symlinks, $publicPath, $storagePath) {
|
||||||
|
$symlinks->push([public_path($publicPath) => storage_path($storagePath)]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return $symlinks->mapWithKeys(fn ($item) => $item); // [[a => b], [c => d]] -> [a => b, c => d]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Determine if the provided path is an existing symlink. */
|
||||||
|
protected static function symlinkExists(string $link): bool
|
||||||
|
{
|
||||||
|
return file_exists($link) && is_link($link);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -9,6 +9,8 @@ use Stancl\Tenancy\Enums\LogMode;
|
||||||
use Stancl\Tenancy\Events\Contracts\TenancyEvent;
|
use Stancl\Tenancy\Events\Contracts\TenancyEvent;
|
||||||
use Stancl\Tenancy\Tenancy;
|
use Stancl\Tenancy\Tenancy;
|
||||||
|
|
||||||
|
// todo finish this feature
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @mixin Tenancy
|
* @mixin Tenancy
|
||||||
*/
|
*/
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,8 @@ namespace Stancl\Tenancy\Contracts;
|
||||||
use Illuminate\Database\Eloquent\Collection;
|
use Illuminate\Database\Eloquent\Collection;
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||||
|
|
||||||
|
// todo move all resource syncing-related things to a separate namespace?
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @property-read Tenant[]|Collection $tenants
|
* @property-read Tenant[]|Collection $tenants
|
||||||
*/
|
*/
|
||||||
|
|
|
||||||
|
|
@ -8,11 +8,11 @@ interface Syncable
|
||||||
{
|
{
|
||||||
public function getGlobalIdentifierKeyName(): string;
|
public function getGlobalIdentifierKeyName(): string;
|
||||||
|
|
||||||
public function getGlobalIdentifierKey();
|
public function getGlobalIdentifierKey(): string|int;
|
||||||
|
|
||||||
public function getCentralModelName(): string;
|
public function getCentralModelName(): string;
|
||||||
|
|
||||||
public function getSyncedAttributeNames(): array;
|
public function getSyncedAttributeNames(): array;
|
||||||
|
|
||||||
public function triggerSyncEvent();
|
public function triggerSyncEvent(): void;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,11 +4,11 @@ declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Contracts;
|
namespace Stancl\Tenancy\Contracts;
|
||||||
|
|
||||||
|
use Closure;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @see \Stancl\Tenancy\Database\Models\Tenant
|
* @see \Stancl\Tenancy\Database\Models\Tenant
|
||||||
*
|
*
|
||||||
* @method __call(string $method, array $parameters) IDE support. This will be a model.
|
|
||||||
* @method static __callStatic(string $method, array $parameters) IDE support. This will be a model.
|
|
||||||
* @mixin \Illuminate\Database\Eloquent\Model
|
* @mixin \Illuminate\Database\Eloquent\Model
|
||||||
*/
|
*/
|
||||||
interface Tenant
|
interface Tenant
|
||||||
|
|
@ -17,14 +17,14 @@ interface Tenant
|
||||||
public function getTenantKeyName(): string;
|
public function getTenantKeyName(): string;
|
||||||
|
|
||||||
/** Get the value of the key used for identifying the tenant. */
|
/** Get the value of the key used for identifying the tenant. */
|
||||||
public function getTenantKey();
|
public function getTenantKey(): int|string;
|
||||||
|
|
||||||
/** Get the value of an internal key. */
|
/** Get the value of an internal key. */
|
||||||
public function getInternal(string $key);
|
public function getInternal(string $key): mixed;
|
||||||
|
|
||||||
/** Set the value of an internal key. */
|
/** Set the value of an internal key. */
|
||||||
public function setInternal(string $key, $value);
|
public function setInternal(string $key, mixed $value): static;
|
||||||
|
|
||||||
/** Run a callback in this tenant's environment. */
|
/** Run a callback in this tenant's environment. */
|
||||||
public function run(callable $callback);
|
public function run(Closure $callback): mixed;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,49 @@ declare(strict_types=1);
|
||||||
namespace Stancl\Tenancy\Contracts;
|
namespace Stancl\Tenancy\Contracts;
|
||||||
|
|
||||||
use Exception;
|
use Exception;
|
||||||
|
use Spatie\Ignition\Contracts\BaseSolution;
|
||||||
|
use Spatie\Ignition\Contracts\ProvidesSolution;
|
||||||
|
|
||||||
abstract class TenantCouldNotBeIdentifiedException extends Exception
|
abstract class TenantCouldNotBeIdentifiedException extends Exception implements ProvidesSolution
|
||||||
{
|
{
|
||||||
|
/** Default solution title. */
|
||||||
|
protected string $solutionTitle = 'Tenant could not be identified';
|
||||||
|
|
||||||
|
/** Default solution description. */
|
||||||
|
protected string $solutionDescription = 'Are you sure this tenant exists?';
|
||||||
|
|
||||||
|
/** Set the message. */
|
||||||
|
protected function tenantCouldNotBeIdentified(string $how): static
|
||||||
|
{
|
||||||
|
$this->message = 'Tenant could not be identified ' . $how;
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Set the solution title. */
|
||||||
|
protected function title(string $solutionTitle): static
|
||||||
|
{
|
||||||
|
$this->solutionTitle = $solutionTitle;
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Set the solution description. */
|
||||||
|
protected function description(string $solutionDescription): static
|
||||||
|
{
|
||||||
|
$this->solutionDescription = $solutionDescription;
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get the Ignition description. */
|
||||||
|
public function getSolution(): BaseSolution
|
||||||
|
{
|
||||||
|
return BaseSolution::create($this->solutionTitle)
|
||||||
|
->setSolutionDescription($this->solutionDescription)
|
||||||
|
->setDocumentationLinks([
|
||||||
|
'Tenants' => 'https://tenancyforlaravel.com/docs/v3/tenants',
|
||||||
|
'Tenant Identification' => 'https://tenancyforlaravel.com/docs/v3/tenant-identification',
|
||||||
|
]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -11,5 +11,5 @@ interface TenantResolver
|
||||||
*
|
*
|
||||||
* @throws TenantCouldNotBeIdentifiedException
|
* @throws TenantCouldNotBeIdentifiedException
|
||||||
*/
|
*/
|
||||||
public function resolve(...$args): Tenant;
|
public function resolve(mixed ...$args): Tenant;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
<?php
|
|
||||||
|
|
||||||
declare(strict_types=1);
|
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Contracts;
|
|
||||||
|
|
||||||
use Stancl\Tenancy\DatabaseConfig;
|
|
||||||
|
|
||||||
interface TenantWithDatabase extends Tenant
|
|
||||||
{
|
|
||||||
public function database(): DatabaseConfig;
|
|
||||||
|
|
||||||
/** Get an internal key. */
|
|
||||||
public function getInternal(string $key);
|
|
||||||
}
|
|
||||||
|
|
@ -4,10 +4,12 @@ declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Contracts;
|
namespace Stancl\Tenancy\Contracts;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
interface UniqueIdentifierGenerator
|
interface UniqueIdentifierGenerator
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Generate a unique identifier.
|
* Generate a unique identifier for a model.
|
||||||
*/
|
*/
|
||||||
public static function generate($resource): string;
|
public static function generate(Model $model): string;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,22 +4,26 @@ declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Controllers;
|
namespace Stancl\Tenancy\Controllers;
|
||||||
|
|
||||||
|
use Closure;
|
||||||
use Illuminate\Routing\Controller;
|
use Illuminate\Routing\Controller;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
class TenantAssetsController extends Controller
|
class TenantAssetsController extends Controller // todo rename this to TenantAssetController & update references in docs
|
||||||
{
|
{
|
||||||
public static $tenancyMiddleware = 'Stancl\Tenancy\Middleware\InitializeTenancyByDomain';
|
public static string|array|Closure $tenancyMiddleware = Stancl\Tenancy\Middleware\InitializeTenancyByDomain::class;
|
||||||
|
|
||||||
public function __construct()
|
public function __construct()
|
||||||
{
|
{
|
||||||
$this->middleware(static::$tenancyMiddleware);
|
$this->middleware(static::$tenancyMiddleware);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function asset($path)
|
public function asset(string $path = null)
|
||||||
{
|
{
|
||||||
|
abort_if($path === null, 404);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return response()->file(storage_path("app/public/$path"));
|
return response()->file(storage_path("app/public/$path"));
|
||||||
} catch (\Throwable $th) {
|
} catch (Throwable) {
|
||||||
abort(404);
|
abort(404);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ trait BelongsToPrimaryModel
|
||||||
{
|
{
|
||||||
abstract public function getRelationshipToPrimaryModel(): string;
|
abstract public function getRelationshipToPrimaryModel(): string;
|
||||||
|
|
||||||
public static function bootBelongsToPrimaryModel()
|
public static function bootBelongsToPrimaryModel(): void
|
||||||
{
|
{
|
||||||
static::addGlobalScope(new ParentModelScope);
|
static::addGlobalScope(new ParentModelScope);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -19,7 +19,7 @@ trait BelongsToTenant
|
||||||
return $this->belongsTo(config('tenancy.tenant_model'), BelongsToTenant::$tenantIdColumn);
|
return $this->belongsTo(config('tenancy.tenant_model'), BelongsToTenant::$tenantIdColumn);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function bootBelongsToTenant()
|
public static function bootBelongsToTenant(): void
|
||||||
{
|
{
|
||||||
static::addGlobalScope(new TenantScope);
|
static::addGlobalScope(new TenantScope);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ namespace Stancl\Tenancy\Database\Concerns;
|
||||||
|
|
||||||
trait ConvertsDomainsToLowercase
|
trait ConvertsDomainsToLowercase
|
||||||
{
|
{
|
||||||
public static function bootConvertsDomainsToLowercase()
|
public static function bootConvertsDomainsToLowercase(): void
|
||||||
{
|
{
|
||||||
static::saving(function ($model) {
|
static::saving(function ($model) {
|
||||||
$model->domain = strtolower($model->domain);
|
$model->domain = strtolower($model->domain);
|
||||||
|
|
|
||||||
|
|
@ -2,9 +2,9 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Concerns;
|
namespace Stancl\Tenancy\Database\Concerns;
|
||||||
|
|
||||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||||
|
|
||||||
trait CreatesDatabaseUsers
|
trait CreatesDatabaseUsers
|
||||||
{
|
{
|
||||||
|
|
@ -8,7 +8,7 @@ use Stancl\Tenancy\Exceptions\DomainOccupiedByOtherTenantException;
|
||||||
|
|
||||||
trait EnsuresDomainIsNotOccupied
|
trait EnsuresDomainIsNotOccupied
|
||||||
{
|
{
|
||||||
public static function bootEnsuresDomainIsNotOccupied()
|
public static function bootEnsuresDomainIsNotOccupied(): void
|
||||||
{
|
{
|
||||||
static::saving(function ($self) {
|
static::saving(function ($self) {
|
||||||
if ($domain = $self->newQuery()->where('domain', $self->domain)->first()) {
|
if ($domain = $self->newQuery()->where('domain', $self->domain)->first()) {
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ use Stancl\Tenancy\Contracts\UniqueIdentifierGenerator;
|
||||||
|
|
||||||
trait GeneratesIds
|
trait GeneratesIds
|
||||||
{
|
{
|
||||||
public static function bootGeneratesIds()
|
public static function bootGeneratesIds(): void
|
||||||
{
|
{
|
||||||
static::creating(function (self $model) {
|
static::creating(function (self $model) {
|
||||||
if (! $model->getKey() && $model->shouldGenerateId()) {
|
if (! $model->getKey() && $model->shouldGenerateId()) {
|
||||||
|
|
|
||||||
|
|
@ -4,8 +4,8 @@ declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Database\Concerns;
|
namespace Stancl\Tenancy\Database\Concerns;
|
||||||
|
|
||||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||||
use Stancl\Tenancy\DatabaseConfig;
|
use Stancl\Tenancy\Database\DatabaseConfig;
|
||||||
|
|
||||||
trait HasDatabase
|
trait HasDatabase
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -2,12 +2,16 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
// todo not sure if this should be in Database\
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Database\Concerns;
|
namespace Stancl\Tenancy\Database\Concerns;
|
||||||
|
|
||||||
use Stancl\Tenancy\Contracts\Domain;
|
use Stancl\Tenancy\Contracts\Domain;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @property-read Domain[]|\Illuminate\Database\Eloquent\Collection $domains
|
* @property-read Domain[]|\Illuminate\Database\Eloquent\Collection $domains
|
||||||
|
* @mixin \Illuminate\Database\Eloquent\Model
|
||||||
|
* @mixin \Stancl\Tenancy\Contracts\Tenant
|
||||||
*/
|
*/
|
||||||
trait HasDomains
|
trait HasDomains
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -6,26 +6,20 @@ namespace Stancl\Tenancy\Database\Concerns;
|
||||||
|
|
||||||
trait HasInternalKeys
|
trait HasInternalKeys
|
||||||
{
|
{
|
||||||
/**
|
/** Get the internal prefix. */
|
||||||
* Get the internal prefix.
|
|
||||||
*/
|
|
||||||
public static function internalPrefix(): string
|
public static function internalPrefix(): string
|
||||||
{
|
{
|
||||||
return 'tenancy_';
|
return 'tenancy_';
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Get an internal key. */
|
||||||
* Get an internal key.
|
public function getInternal(string $key): mixed
|
||||||
*/
|
|
||||||
public function getInternal(string $key)
|
|
||||||
{
|
{
|
||||||
return $this->getAttribute(static::internalPrefix() . $key);
|
return $this->getAttribute(static::internalPrefix() . $key);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Set internal key. */
|
||||||
* Set internal key.
|
public function setInternal(string $key, mixed $value): static
|
||||||
*/
|
|
||||||
public function setInternal(string $key, $value)
|
|
||||||
{
|
{
|
||||||
$this->setAttribute(static::internalPrefix() . $key, $value);
|
$this->setAttribute(static::internalPrefix() . $key, $value);
|
||||||
|
|
||||||
|
|
|
||||||
21
src/Database/Concerns/InitializationHelpers.php
Normal file
21
src/Database/Concerns/InitializationHelpers.php
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Stancl\Tenancy\Database\Concerns;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @mixin \Stancl\Tenancy\Contracts\Tenant
|
||||||
|
*/
|
||||||
|
trait InitializationHelpers
|
||||||
|
{
|
||||||
|
public function enter(): void
|
||||||
|
{
|
||||||
|
tenancy()->initialize($this);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function leave(): void
|
||||||
|
{
|
||||||
|
tenancy()->end();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -16,7 +16,7 @@ trait InvalidatesResolverCache
|
||||||
Resolvers\RequestDataTenantResolver::class,
|
Resolvers\RequestDataTenantResolver::class,
|
||||||
];
|
];
|
||||||
|
|
||||||
public static function bootInvalidatesResolverCache()
|
public static function bootInvalidatesResolverCache(): void
|
||||||
{
|
{
|
||||||
static::saved(function (Tenant $tenant) {
|
static::saved(function (Tenant $tenant) {
|
||||||
foreach (static::$resolvers as $resolver) {
|
foreach (static::$resolvers as $resolver) {
|
||||||
|
|
|
||||||
|
|
@ -19,7 +19,7 @@ trait InvalidatesTenantsResolverCache
|
||||||
Resolvers\RequestDataTenantResolver::class,
|
Resolvers\RequestDataTenantResolver::class,
|
||||||
];
|
];
|
||||||
|
|
||||||
public static function bootInvalidatesTenantsResolverCache()
|
public static function bootInvalidatesTenantsResolverCache(): void
|
||||||
{
|
{
|
||||||
static::saved(function (Model $model) {
|
static::saved(function (Model $model) {
|
||||||
foreach (static::$resolvers as $resolver) {
|
foreach (static::$resolvers as $resolver) {
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ use Stancl\Tenancy\Events\SyncedResourceSaved;
|
||||||
|
|
||||||
trait ResourceSyncing
|
trait ResourceSyncing
|
||||||
{
|
{
|
||||||
public static function bootResourceSyncing()
|
public static function bootResourceSyncing(): void
|
||||||
{
|
{
|
||||||
static::saved(function (Syncable $model) {
|
static::saved(function (Syncable $model) {
|
||||||
/** @var ResourceSyncing $model */
|
/** @var ResourceSyncing $model */
|
||||||
|
|
@ -27,7 +27,7 @@ trait ResourceSyncing
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public function triggerSyncEvent()
|
public function triggerSyncEvent(): void
|
||||||
{
|
{
|
||||||
/** @var Syncable $this */
|
/** @var Syncable $this */
|
||||||
event(new SyncedResourceSaved($this, tenant()));
|
event(new SyncedResourceSaved($this, tenant()));
|
||||||
|
|
|
||||||
|
|
@ -4,15 +4,17 @@ declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Database\Concerns;
|
namespace Stancl\Tenancy\Database\Concerns;
|
||||||
|
|
||||||
|
use Closure;
|
||||||
use Stancl\Tenancy\Contracts\Tenant;
|
use Stancl\Tenancy\Contracts\Tenant;
|
||||||
|
|
||||||
trait TenantRun
|
trait TenantRun
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Run a callback in this tenant's context.
|
* Run a callback in this tenant's context.
|
||||||
* Atomic, safely reverts to previous context.
|
*
|
||||||
|
* This method is atomic and safely reverts to the previous context.
|
||||||
*/
|
*/
|
||||||
public function run(callable $callback)
|
public function run(Closure $callback): mixed
|
||||||
{
|
{
|
||||||
/** @var Tenant $this */
|
/** @var Tenant $this */
|
||||||
$originalTenant = tenant();
|
$originalTenant = tenant();
|
||||||
|
|
|
||||||
|
|
@ -2,15 +2,18 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Contracts;
|
namespace Stancl\Tenancy\Database\Contracts;
|
||||||
|
|
||||||
use Stancl\Tenancy\DatabaseConfig;
|
use Stancl\Tenancy\Database\DatabaseConfig;
|
||||||
|
|
||||||
interface ManagesDatabaseUsers extends TenantDatabaseManager
|
interface ManagesDatabaseUsers extends TenantDatabaseManager
|
||||||
{
|
{
|
||||||
|
/** Create a database user. */
|
||||||
public function createUser(DatabaseConfig $databaseConfig): bool;
|
public function createUser(DatabaseConfig $databaseConfig): bool;
|
||||||
|
|
||||||
|
/** Delete a database user. */
|
||||||
public function deleteUser(DatabaseConfig $databaseConfig): bool;
|
public function deleteUser(DatabaseConfig $databaseConfig): bool;
|
||||||
|
|
||||||
|
/** Does a database user exist? */
|
||||||
public function userExists(string $username): bool;
|
public function userExists(string $username): bool;
|
||||||
}
|
}
|
||||||
|
|
@ -2,30 +2,22 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Contracts;
|
namespace Stancl\Tenancy\Database\Contracts;
|
||||||
|
|
||||||
use Stancl\Tenancy\Exceptions\NoConnectionSetException;
|
use Stancl\Tenancy\Database\Exceptions\NoConnectionSetException;
|
||||||
|
|
||||||
interface TenantDatabaseManager
|
interface TenantDatabaseManager
|
||||||
{
|
{
|
||||||
/**
|
/** Create a database. */
|
||||||
* Create a database.
|
|
||||||
*/
|
|
||||||
public function createDatabase(TenantWithDatabase $tenant): bool;
|
public function createDatabase(TenantWithDatabase $tenant): bool;
|
||||||
|
|
||||||
/**
|
/** Delete a database. */
|
||||||
* Delete a database.
|
|
||||||
*/
|
|
||||||
public function deleteDatabase(TenantWithDatabase $tenant): bool;
|
public function deleteDatabase(TenantWithDatabase $tenant): bool;
|
||||||
|
|
||||||
/**
|
/** Does a database exist? */
|
||||||
* Does a database exist.
|
|
||||||
*/
|
|
||||||
public function databaseExists(string $name): bool;
|
public function databaseExists(string $name): bool;
|
||||||
|
|
||||||
/**
|
/** Construct a DB connection config array. */
|
||||||
* Make a DB connection config array.
|
|
||||||
*/
|
|
||||||
public function makeConnectionConfig(array $baseConfig, string $databaseName): array;
|
public function makeConnectionConfig(array $baseConfig, string $databaseName): array;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
13
src/Database/Contracts/TenantWithDatabase.php
Normal file
13
src/Database/Contracts/TenantWithDatabase.php
Normal file
|
|
@ -0,0 +1,13 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Stancl\Tenancy\Database\Contracts;
|
||||||
|
|
||||||
|
use Stancl\Tenancy\Contracts\Tenant;
|
||||||
|
use Stancl\Tenancy\Database\DatabaseConfig;
|
||||||
|
|
||||||
|
interface TenantWithDatabase extends Tenant
|
||||||
|
{
|
||||||
|
public function database(): DatabaseConfig;
|
||||||
|
}
|
||||||
|
|
@ -2,29 +2,27 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy;
|
namespace Stancl\Tenancy\Database;
|
||||||
|
|
||||||
|
use Closure;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Support\Facades\Hash;
|
use Illuminate\Support\Facades\Hash;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
use Stancl\Tenancy\Contracts\ManagesDatabaseUsers;
|
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase as Tenant;
|
||||||
use Stancl\Tenancy\Contracts\TenantDatabaseManager;
|
|
||||||
use Stancl\Tenancy\Contracts\TenantWithDatabase as Tenant;
|
|
||||||
use Stancl\Tenancy\Exceptions\DatabaseManagerNotRegisteredException;
|
|
||||||
|
|
||||||
class DatabaseConfig
|
class DatabaseConfig
|
||||||
{
|
{
|
||||||
/** @var Tenant|Model */
|
/** The tenant whose database we're dealing with. */
|
||||||
public $tenant;
|
public Tenant&Model $tenant;
|
||||||
|
|
||||||
/** @var callable */
|
/** Database username generator (can be set by the developer.) */
|
||||||
public static $usernameGenerator;
|
public static Closure|null $usernameGenerator = null;
|
||||||
|
|
||||||
/** @var callable */
|
/** Database password generator (can be set by the developer.) */
|
||||||
public static $passwordGenerator;
|
public static Closure|null $passwordGenerator = null;
|
||||||
|
|
||||||
/** @var callable */
|
/** Database name generator (can be set by the developer.) */
|
||||||
public static $databaseNameGenerator;
|
public static Closure|null $databaseNameGenerator = null;
|
||||||
|
|
||||||
public static function __constructStatic(): void
|
public static function __constructStatic(): void
|
||||||
{
|
{
|
||||||
|
|
@ -48,17 +46,17 @@ class DatabaseConfig
|
||||||
$this->tenant = $tenant;
|
$this->tenant = $tenant;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function generateDatabaseNamesUsing(callable $databaseNameGenerator): void
|
public static function generateDatabaseNamesUsing(Closure $databaseNameGenerator): void
|
||||||
{
|
{
|
||||||
static::$databaseNameGenerator = $databaseNameGenerator;
|
static::$databaseNameGenerator = $databaseNameGenerator;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function generateUsernamesUsing(callable $usernameGenerator): void
|
public static function generateUsernamesUsing(Closure $usernameGenerator): void
|
||||||
{
|
{
|
||||||
static::$usernameGenerator = $usernameGenerator;
|
static::$usernameGenerator = $usernameGenerator;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function generatePasswordsUsing(callable $passwordGenerator): void
|
public static function generatePasswordsUsing(Closure $passwordGenerator): void
|
||||||
{
|
{
|
||||||
static::$passwordGenerator = $passwordGenerator;
|
static::$passwordGenerator = $passwordGenerator;
|
||||||
}
|
}
|
||||||
|
|
@ -85,7 +83,7 @@ class DatabaseConfig
|
||||||
{
|
{
|
||||||
$this->tenant->setInternal('db_name', $this->getName() ?? (static::$databaseNameGenerator)($this->tenant));
|
$this->tenant->setInternal('db_name', $this->getName() ?? (static::$databaseNameGenerator)($this->tenant));
|
||||||
|
|
||||||
if ($this->manager() instanceof ManagesDatabaseUsers) {
|
if ($this->manager() instanceof Contracts\ManagesDatabaseUsers) {
|
||||||
$this->tenant->setInternal('db_username', $this->getUsername() ?? (static::$usernameGenerator)($this->tenant));
|
$this->tenant->setInternal('db_username', $this->getUsername() ?? (static::$usernameGenerator)($this->tenant));
|
||||||
$this->tenant->setInternal('db_password', $this->getPassword() ?? (static::$passwordGenerator)($this->tenant));
|
$this->tenant->setInternal('db_password', $this->getPassword() ?? (static::$passwordGenerator)($this->tenant));
|
||||||
}
|
}
|
||||||
|
|
@ -142,20 +140,18 @@ class DatabaseConfig
|
||||||
}, []);
|
}, []);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Get the TenantDatabaseManager for this tenant's connection. */
|
||||||
* Get the TenantDatabaseManager for this tenant's connection.
|
public function manager(): Contracts\TenantDatabaseManager
|
||||||
*/
|
|
||||||
public function manager(): TenantDatabaseManager
|
|
||||||
{
|
{
|
||||||
$driver = config("database.connections.{$this->getTemplateConnectionName()}.driver");
|
$driver = config("database.connections.{$this->getTemplateConnectionName()}.driver");
|
||||||
|
|
||||||
$databaseManagers = config('tenancy.database.managers');
|
$databaseManagers = config('tenancy.database.managers');
|
||||||
|
|
||||||
if (! array_key_exists($driver, $databaseManagers)) {
|
if (! array_key_exists($driver, $databaseManagers)) {
|
||||||
throw new DatabaseManagerNotRegisteredException($driver);
|
throw new Exceptions\DatabaseManagerNotRegisteredException($driver);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @var TenantDatabaseManager $databaseManager */
|
/** @var Contracts\TenantDatabaseManager $databaseManager */
|
||||||
$databaseManager = app($databaseManagers[$driver]);
|
$databaseManager = app($databaseManagers[$driver]);
|
||||||
|
|
||||||
$databaseManager->setConnection($this->getTemplateConnectionName());
|
$databaseManager->setConnection($this->getTemplateConnectionName());
|
||||||
|
|
@ -7,12 +7,8 @@ namespace Stancl\Tenancy\Database;
|
||||||
use Illuminate\Config\Repository;
|
use Illuminate\Config\Repository;
|
||||||
use Illuminate\Contracts\Foundation\Application;
|
use Illuminate\Contracts\Foundation\Application;
|
||||||
use Illuminate\Database\DatabaseManager as BaseDatabaseManager;
|
use Illuminate\Database\DatabaseManager as BaseDatabaseManager;
|
||||||
use Stancl\Tenancy\Contracts\ManagesDatabaseUsers;
|
|
||||||
use Stancl\Tenancy\Contracts\TenantCannotBeCreatedException;
|
use Stancl\Tenancy\Contracts\TenantCannotBeCreatedException;
|
||||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||||
use Stancl\Tenancy\Exceptions\DatabaseManagerNotRegisteredException;
|
|
||||||
use Stancl\Tenancy\Exceptions\TenantDatabaseAlreadyExistsException;
|
|
||||||
use Stancl\Tenancy\Exceptions\TenantDatabaseUserAlreadyExistsException;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @internal Class is subject to breaking changes in minor and patch versions.
|
* @internal Class is subject to breaking changes in minor and patch versions.
|
||||||
|
|
@ -38,7 +34,7 @@ class DatabaseManager
|
||||||
/**
|
/**
|
||||||
* Connect to a tenant's database.
|
* Connect to a tenant's database.
|
||||||
*/
|
*/
|
||||||
public function connectToTenant(TenantWithDatabase $tenant)
|
public function connectToTenant(TenantWithDatabase $tenant): void
|
||||||
{
|
{
|
||||||
$this->purgeTenantConnection();
|
$this->purgeTenantConnection();
|
||||||
$this->createTenantConnection($tenant);
|
$this->createTenantConnection($tenant);
|
||||||
|
|
@ -48,7 +44,7 @@ class DatabaseManager
|
||||||
/**
|
/**
|
||||||
* Reconnect to the default non-tenant connection.
|
* Reconnect to the default non-tenant connection.
|
||||||
*/
|
*/
|
||||||
public function reconnectToCentral()
|
public function reconnectToCentral(): void
|
||||||
{
|
{
|
||||||
$this->purgeTenantConnection();
|
$this->purgeTenantConnection();
|
||||||
$this->setDefaultConnection($this->config->get('tenancy.database.central_connection'));
|
$this->setDefaultConnection($this->config->get('tenancy.database.central_connection'));
|
||||||
|
|
@ -57,7 +53,7 @@ class DatabaseManager
|
||||||
/**
|
/**
|
||||||
* Change the default database connection config.
|
* Change the default database connection config.
|
||||||
*/
|
*/
|
||||||
public function setDefaultConnection(string $connection)
|
public function setDefaultConnection(string $connection): void
|
||||||
{
|
{
|
||||||
$this->config['database.default'] = $connection;
|
$this->config['database.default'] = $connection;
|
||||||
$this->database->setDefaultConnection($connection);
|
$this->database->setDefaultConnection($connection);
|
||||||
|
|
@ -66,7 +62,7 @@ class DatabaseManager
|
||||||
/**
|
/**
|
||||||
* Create the tenant database connection.
|
* Create the tenant database connection.
|
||||||
*/
|
*/
|
||||||
public function createTenantConnection(TenantWithDatabase $tenant)
|
public function createTenantConnection(TenantWithDatabase $tenant): void
|
||||||
{
|
{
|
||||||
$this->config['database.connections.tenant'] = $tenant->database()->connection();
|
$this->config['database.connections.tenant'] = $tenant->database()->connection();
|
||||||
}
|
}
|
||||||
|
|
@ -74,7 +70,7 @@ class DatabaseManager
|
||||||
/**
|
/**
|
||||||
* Purge the tenant database connection.
|
* Purge the tenant database connection.
|
||||||
*/
|
*/
|
||||||
public function purgeTenantConnection()
|
public function purgeTenantConnection(): void
|
||||||
{
|
{
|
||||||
if (array_key_exists('tenant', $this->database->getConnections())) {
|
if (array_key_exists('tenant', $this->database->getConnections())) {
|
||||||
$this->database->purge('tenant');
|
$this->database->purge('tenant');
|
||||||
|
|
@ -95,11 +91,11 @@ class DatabaseManager
|
||||||
$manager = $tenant->database()->manager();
|
$manager = $tenant->database()->manager();
|
||||||
|
|
||||||
if ($manager->databaseExists($database = $tenant->database()->getName())) {
|
if ($manager->databaseExists($database = $tenant->database()->getName())) {
|
||||||
throw new TenantDatabaseAlreadyExistsException($database);
|
throw new Exceptions\TenantDatabaseAlreadyExistsException($database);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($manager instanceof ManagesDatabaseUsers && $manager->userExists($username = $tenant->database()->getUsername())) {
|
if ($manager instanceof Contracts\ManagesDatabaseUsers && $manager->userExists($username = $tenant->database()->getUsername())) {
|
||||||
throw new TenantDatabaseUserAlreadyExistsException($username);
|
throw new Exceptions\TenantDatabaseUserAlreadyExistsException($username);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,15 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Stancl\Tenancy\Database\Exceptions;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
|
|
||||||
|
class DatabaseManagerNotRegisteredException extends Exception
|
||||||
|
{
|
||||||
|
public function __construct(string $driver)
|
||||||
|
{
|
||||||
|
parent::__construct("Database manager for driver $driver is not registered.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -2,13 +2,13 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Exceptions;
|
namespace Stancl\Tenancy\Database\Exceptions;
|
||||||
|
|
||||||
use Exception;
|
use Exception;
|
||||||
|
|
||||||
class NoConnectionSetException extends Exception
|
class NoConnectionSetException extends Exception
|
||||||
{
|
{
|
||||||
public function __construct($manager)
|
public function __construct(string $manager)
|
||||||
{
|
{
|
||||||
parent::__construct("No connection was set on this $manager instance.");
|
parent::__construct("No connection was set on this $manager instance.");
|
||||||
}
|
}
|
||||||
|
|
@ -2,24 +2,20 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Exceptions;
|
namespace Stancl\Tenancy\Database\Exceptions;
|
||||||
|
|
||||||
use Stancl\Tenancy\Contracts\TenantCannotBeCreatedException;
|
use Stancl\Tenancy\Contracts\TenantCannotBeCreatedException;
|
||||||
|
|
||||||
class TenantDatabaseAlreadyExistsException extends TenantCannotBeCreatedException
|
class TenantDatabaseAlreadyExistsException extends TenantCannotBeCreatedException
|
||||||
{
|
{
|
||||||
/** @var string */
|
public function __construct(
|
||||||
protected $database;
|
protected string $database,
|
||||||
|
) {
|
||||||
|
parent::__construct();
|
||||||
|
}
|
||||||
|
|
||||||
public function reason(): string
|
public function reason(): string
|
||||||
{
|
{
|
||||||
return "Database {$this->database} already exists.";
|
return "Database {$this->database} already exists.";
|
||||||
}
|
}
|
||||||
|
|
||||||
public function __construct(string $database)
|
|
||||||
{
|
|
||||||
$this->database = $database;
|
|
||||||
|
|
||||||
parent::__construct();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
@ -2,13 +2,13 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Exceptions;
|
namespace Stancl\Tenancy\Database\Exceptions;
|
||||||
|
|
||||||
use Exception;
|
use Exception;
|
||||||
|
|
||||||
class TenantDatabaseDoesNotExistException extends Exception
|
class TenantDatabaseDoesNotExistException extends Exception
|
||||||
{
|
{
|
||||||
public function __construct($database)
|
public function __construct(string $database)
|
||||||
{
|
{
|
||||||
parent::__construct("Database $database does not exist.");
|
parent::__construct("Database $database does not exist.");
|
||||||
}
|
}
|
||||||
|
|
@ -2,24 +2,20 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Exceptions;
|
namespace Stancl\Tenancy\Database\Exceptions;
|
||||||
|
|
||||||
use Stancl\Tenancy\Contracts\TenantCannotBeCreatedException;
|
use Stancl\Tenancy\Contracts\TenantCannotBeCreatedException;
|
||||||
|
|
||||||
class TenantDatabaseUserAlreadyExistsException extends TenantCannotBeCreatedException
|
class TenantDatabaseUserAlreadyExistsException extends TenantCannotBeCreatedException
|
||||||
{
|
{
|
||||||
/** @var string */
|
public function __construct(
|
||||||
protected $user;
|
protected string $user,
|
||||||
|
) {
|
||||||
|
parent::__construct();
|
||||||
|
}
|
||||||
|
|
||||||
public function reason(): string
|
public function reason(): string
|
||||||
{
|
{
|
||||||
return "Database user {$this->user} already exists.";
|
return "Database user {$this->user} already exists.";
|
||||||
}
|
}
|
||||||
|
|
||||||
public function __construct(string $user)
|
|
||||||
{
|
|
||||||
parent::__construct();
|
|
||||||
|
|
||||||
$this->user = $user;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||||
namespace Stancl\Tenancy\Database\Models;
|
namespace Stancl\Tenancy\Database\Models;
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
use Stancl\Tenancy\Contracts;
|
use Stancl\Tenancy\Contracts;
|
||||||
use Stancl\Tenancy\Contracts\Tenant;
|
use Stancl\Tenancy\Contracts\Tenant;
|
||||||
use Stancl\Tenancy\Database\Concerns;
|
use Stancl\Tenancy\Database\Concerns;
|
||||||
|
|
@ -25,7 +26,7 @@ class Domain extends Model implements Contracts\Domain
|
||||||
|
|
||||||
protected $guarded = [];
|
protected $guarded = [];
|
||||||
|
|
||||||
public function tenant()
|
public function tenant(): BelongsTo
|
||||||
{
|
{
|
||||||
return $this->belongsTo(config('tenancy.tenant_model'));
|
return $this->belongsTo(config('tenancy.tenant_model'));
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,17 +5,20 @@ declare(strict_types=1);
|
||||||
namespace Stancl\Tenancy\Database\Models;
|
namespace Stancl\Tenancy\Database\Models;
|
||||||
|
|
||||||
use Carbon\Carbon;
|
use Carbon\Carbon;
|
||||||
|
use Illuminate\Contracts\Auth\StatefulGuard;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Support\Facades\Auth;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
use Stancl\Tenancy\Database\Concerns\CentralConnection;
|
use Stancl\Tenancy\Database\Concerns\CentralConnection;
|
||||||
|
use Stancl\Tenancy\Exceptions\StatefulGuardRequiredException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param string $token
|
* @property string $token
|
||||||
* @param string $tenant_id
|
* @property string $tenant_id
|
||||||
* @param string $user_id
|
* @property string $user_id
|
||||||
* @param string $auth_guard
|
* @property string $auth_guard
|
||||||
* @param string $redirect_url
|
* @property string $redirect_url
|
||||||
* @param Carbon $created_at
|
* @property Carbon $created_at
|
||||||
*/
|
*/
|
||||||
class ImpersonationToken extends Model
|
class ImpersonationToken extends Model
|
||||||
{
|
{
|
||||||
|
|
@ -35,14 +38,18 @@ class ImpersonationToken extends Model
|
||||||
'created_at',
|
'created_at',
|
||||||
];
|
];
|
||||||
|
|
||||||
public static function boot()
|
public static function booted(): void
|
||||||
{
|
{
|
||||||
parent::boot();
|
|
||||||
|
|
||||||
static::creating(function ($model) {
|
static::creating(function ($model) {
|
||||||
|
$authGuard = $model->auth_guard ?? config('auth.defaults.guard');
|
||||||
|
|
||||||
|
if (! Auth::guard($authGuard) instanceof StatefulGuard) {
|
||||||
|
throw new StatefulGuardRequiredException($authGuard);
|
||||||
|
}
|
||||||
|
|
||||||
$model->created_at = $model->created_at ?? $model->freshTimestamp();
|
$model->created_at = $model->created_at ?? $model->freshTimestamp();
|
||||||
$model->token = $model->token ?? Str::random(128);
|
$model->token = $model->token ?? Str::random(128);
|
||||||
$model->auth_guard = $model->auth_guard ?? config('auth.defaults.guard');
|
$model->auth_guard = $authGuard;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -26,6 +26,7 @@ class Tenant extends Model implements Contracts\Tenant
|
||||||
Concerns\HasDataColumn,
|
Concerns\HasDataColumn,
|
||||||
Concerns\HasInternalKeys,
|
Concerns\HasInternalKeys,
|
||||||
Concerns\TenantRun,
|
Concerns\TenantRun,
|
||||||
|
Concerns\InitializationHelpers,
|
||||||
Concerns\InvalidatesResolverCache;
|
Concerns\InvalidatesResolverCache;
|
||||||
|
|
||||||
protected $table = 'tenants';
|
protected $table = 'tenants';
|
||||||
|
|
@ -39,7 +40,7 @@ class Tenant extends Model implements Contracts\Tenant
|
||||||
return 'id';
|
return 'id';
|
||||||
}
|
}
|
||||||
|
|
||||||
public function getTenantKey()
|
public function getTenantKey(): int|string
|
||||||
{
|
{
|
||||||
return $this->getAttribute($this->getTenantKeyName());
|
return $this->getAttribute($this->getTenantKeyName());
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -9,10 +9,8 @@ use Stancl\Tenancy\Contracts\Syncable;
|
||||||
|
|
||||||
class TenantPivot extends Pivot
|
class TenantPivot extends Pivot
|
||||||
{
|
{
|
||||||
public static function boot()
|
public static function booted(): void
|
||||||
{
|
{
|
||||||
parent::boot();
|
|
||||||
|
|
||||||
static::saved(function (self $pivot) {
|
static::saved(function (self $pivot) {
|
||||||
$parent = $pivot->pivotParent;
|
$parent = $pivot->pivotParent;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ use Illuminate\Database\Eloquent\Scope;
|
||||||
|
|
||||||
class ParentModelScope implements Scope
|
class ParentModelScope implements Scope
|
||||||
{
|
{
|
||||||
public function apply(Builder $builder, Model $model)
|
public function apply(Builder $builder, Model $model): void
|
||||||
{
|
{
|
||||||
if (! tenancy()->initialized) {
|
if (! tenancy()->initialized) {
|
||||||
return;
|
return;
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Database;
|
namespace Stancl\Tenancy\Database;
|
||||||
|
|
||||||
|
use Closure;
|
||||||
use Illuminate\Database\Eloquent\Collection;
|
use Illuminate\Database\Eloquent\Collection;
|
||||||
use Stancl\Tenancy\Contracts\Tenant;
|
use Stancl\Tenancy\Contracts\Tenant;
|
||||||
|
|
||||||
|
|
@ -16,7 +17,7 @@ use Stancl\Tenancy\Contracts\Tenant;
|
||||||
*/
|
*/
|
||||||
class TenantCollection extends Collection
|
class TenantCollection extends Collection
|
||||||
{
|
{
|
||||||
public function runForEach(callable $callable): self
|
public function runForEach(Closure $callable): self
|
||||||
{
|
{
|
||||||
tenancy()->runForMultiple($this->items, $callable);
|
tenancy()->runForMultiple($this->items, $callable);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,29 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Stancl\Tenancy\Database\TenantDatabaseManagers;
|
||||||
|
|
||||||
|
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||||
|
|
||||||
|
class MicrosoftSQLDatabaseManager extends TenantDatabaseManager
|
||||||
|
{
|
||||||
|
public function createDatabase(TenantWithDatabase $tenant): bool
|
||||||
|
{
|
||||||
|
$database = $tenant->database()->getName();
|
||||||
|
$charset = $this->database()->getConfig('charset');
|
||||||
|
$collation = $this->database()->getConfig('collation'); // todo check why these are not used
|
||||||
|
|
||||||
|
return $this->database()->statement("CREATE DATABASE [{$database}]");
|
||||||
|
}
|
||||||
|
|
||||||
|
public function deleteDatabase(TenantWithDatabase $tenant): bool
|
||||||
|
{
|
||||||
|
return $this->database()->statement("DROP DATABASE [{$tenant->database()->getName()}]");
|
||||||
|
}
|
||||||
|
|
||||||
|
public function databaseExists(string $name): bool
|
||||||
|
{
|
||||||
|
return (bool) $this->database()->select("SELECT name FROM master.sys.databases WHERE name = '$name'");
|
||||||
|
}
|
||||||
|
}
|
||||||
29
src/Database/TenantDatabaseManagers/MySQLDatabaseManager.php
Normal file
29
src/Database/TenantDatabaseManagers/MySQLDatabaseManager.php
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Stancl\Tenancy\Database\TenantDatabaseManagers;
|
||||||
|
|
||||||
|
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||||
|
|
||||||
|
class MySQLDatabaseManager extends TenantDatabaseManager
|
||||||
|
{
|
||||||
|
public function createDatabase(TenantWithDatabase $tenant): bool
|
||||||
|
{
|
||||||
|
$database = $tenant->database()->getName();
|
||||||
|
$charset = $this->database()->getConfig('charset');
|
||||||
|
$collation = $this->database()->getConfig('collation');
|
||||||
|
|
||||||
|
return $this->database()->statement("CREATE DATABASE `{$database}` CHARACTER SET `$charset` COLLATE `$collation`");
|
||||||
|
}
|
||||||
|
|
||||||
|
public function deleteDatabase(TenantWithDatabase $tenant): bool
|
||||||
|
{
|
||||||
|
return $this->database()->statement("DROP DATABASE `{$tenant->database()->getName()}`");
|
||||||
|
}
|
||||||
|
|
||||||
|
public function databaseExists(string $name): bool
|
||||||
|
{
|
||||||
|
return (bool) $this->database()->select("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$name'");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -2,11 +2,11 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\TenantDatabaseManagers;
|
namespace Stancl\Tenancy\Database\TenantDatabaseManagers;
|
||||||
|
|
||||||
use Stancl\Tenancy\Concerns\CreatesDatabaseUsers;
|
use Stancl\Tenancy\Database\Concerns\CreatesDatabaseUsers;
|
||||||
use Stancl\Tenancy\Contracts\ManagesDatabaseUsers;
|
use Stancl\Tenancy\Database\Contracts\ManagesDatabaseUsers;
|
||||||
use Stancl\Tenancy\DatabaseConfig;
|
use Stancl\Tenancy\Database\DatabaseConfig;
|
||||||
|
|
||||||
class PermissionControlledMySQLDatabaseManager extends MySQLDatabaseManager implements ManagesDatabaseUsers
|
class PermissionControlledMySQLDatabaseManager extends MySQLDatabaseManager implements ManagesDatabaseUsers
|
||||||
{
|
{
|
||||||
|
|
@ -54,11 +54,4 @@ class PermissionControlledMySQLDatabaseManager extends MySQLDatabaseManager impl
|
||||||
{
|
{
|
||||||
return (bool) $this->database()->select("SELECT count(*) FROM mysql.user WHERE user = '$username'")[0]->{'count(*)'};
|
return (bool) $this->database()->select("SELECT count(*) FROM mysql.user WHERE user = '$username'")[0]->{'count(*)'};
|
||||||
}
|
}
|
||||||
|
|
||||||
public function makeConnectionConfig(array $baseConfig, string $databaseName): array
|
|
||||||
{
|
|
||||||
$baseConfig['database'] = $databaseName;
|
|
||||||
|
|
||||||
return $baseConfig;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
@ -0,0 +1,25 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Stancl\Tenancy\Database\TenantDatabaseManagers;
|
||||||
|
|
||||||
|
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||||
|
|
||||||
|
class PostgreSQLDatabaseManager extends TenantDatabaseManager
|
||||||
|
{
|
||||||
|
public function createDatabase(TenantWithDatabase $tenant): bool
|
||||||
|
{
|
||||||
|
return $this->database()->statement("CREATE DATABASE \"{$tenant->database()->getName()}\" WITH TEMPLATE=template0");
|
||||||
|
}
|
||||||
|
|
||||||
|
public function deleteDatabase(TenantWithDatabase $tenant): bool
|
||||||
|
{
|
||||||
|
return $this->database()->statement("DROP DATABASE \"{$tenant->database()->getName()}\"");
|
||||||
|
}
|
||||||
|
|
||||||
|
public function databaseExists(string $name): bool
|
||||||
|
{
|
||||||
|
return (bool) $this->database()->select("SELECT datname FROM pg_database WHERE datname = '$name'");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -2,33 +2,12 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\TenantDatabaseManagers;
|
namespace Stancl\Tenancy\Database\TenantDatabaseManagers;
|
||||||
|
|
||||||
use Illuminate\Database\Connection;
|
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||||
use Illuminate\Support\Facades\DB;
|
|
||||||
use Stancl\Tenancy\Contracts\TenantDatabaseManager;
|
|
||||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
|
||||||
use Stancl\Tenancy\Exceptions\NoConnectionSetException;
|
|
||||||
|
|
||||||
class PostgreSQLSchemaManager implements TenantDatabaseManager
|
class PostgreSQLSchemaManager extends TenantDatabaseManager
|
||||||
{
|
{
|
||||||
/** @var string */
|
|
||||||
protected $connection;
|
|
||||||
|
|
||||||
protected function database(): Connection
|
|
||||||
{
|
|
||||||
if ($this->connection === null) {
|
|
||||||
throw new NoConnectionSetException(static::class);
|
|
||||||
}
|
|
||||||
|
|
||||||
return DB::connection($this->connection);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function setConnection(string $connection): void
|
|
||||||
{
|
|
||||||
$this->connection = $connection;
|
|
||||||
}
|
|
||||||
|
|
||||||
public function createDatabase(TenantWithDatabase $tenant): bool
|
public function createDatabase(TenantWithDatabase $tenant): bool
|
||||||
{
|
{
|
||||||
return $this->database()->statement("CREATE SCHEMA \"{$tenant->database()->getName()}\"");
|
return $this->database()->statement("CREATE SCHEMA \"{$tenant->database()->getName()}\"");
|
||||||
|
|
@ -0,0 +1,61 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Stancl\Tenancy\Database\TenantDatabaseManagers;
|
||||||
|
|
||||||
|
use Stancl\Tenancy\Database\Contracts\TenantDatabaseManager;
|
||||||
|
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||||
|
use Throwable;
|
||||||
|
|
||||||
|
class SQLiteDatabaseManager implements TenantDatabaseManager
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* SQLite Database path without ending slash.
|
||||||
|
*/
|
||||||
|
public static string|null $path = null;
|
||||||
|
|
||||||
|
public function createDatabase(TenantWithDatabase $tenant): bool
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
return (bool) file_put_contents($this->getPath($tenant->database()->getName()), '');
|
||||||
|
} catch (Throwable) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function deleteDatabase(TenantWithDatabase $tenant): bool
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
return unlink($this->getPath($tenant->database()->getName()));
|
||||||
|
} catch (Throwable) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function databaseExists(string $name): bool
|
||||||
|
{
|
||||||
|
return file_exists($this->getPath($name));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function makeConnectionConfig(array $baseConfig, string $databaseName): array
|
||||||
|
{
|
||||||
|
$baseConfig['database'] = database_path($databaseName);
|
||||||
|
|
||||||
|
return $baseConfig;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setConnection(string $connection): void
|
||||||
|
{
|
||||||
|
//
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getPath(string $name): string
|
||||||
|
{
|
||||||
|
if (static::$path) {
|
||||||
|
return static::$path . DIRECTORY_SEPARATOR . $name;
|
||||||
|
}
|
||||||
|
|
||||||
|
return database_path($name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,37 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Stancl\Tenancy\Database\TenantDatabaseManagers;
|
||||||
|
|
||||||
|
use Illuminate\Database\Connection;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Stancl\Tenancy\Database\Contracts\TenantDatabaseManager as Contract;
|
||||||
|
use Stancl\Tenancy\Database\Exceptions\NoConnectionSetException;
|
||||||
|
|
||||||
|
abstract class TenantDatabaseManager implements Contract // todo better naming?
|
||||||
|
{
|
||||||
|
/** The database connection to the server. */
|
||||||
|
protected string $connection;
|
||||||
|
|
||||||
|
protected function database(): Connection
|
||||||
|
{
|
||||||
|
if (! isset($this->connection)) {
|
||||||
|
throw new NoConnectionSetException(static::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
return DB::connection($this->connection);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function setConnection(string $connection): void
|
||||||
|
{
|
||||||
|
$this->connection = $connection;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function makeConnectionConfig(array $baseConfig, string $databaseName): array
|
||||||
|
{
|
||||||
|
$baseConfig['database'] = $databaseName;
|
||||||
|
|
||||||
|
return $baseConfig;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -8,11 +8,8 @@ use Stancl\Tenancy\Tenancy;
|
||||||
|
|
||||||
abstract class TenancyEvent
|
abstract class TenancyEvent
|
||||||
{
|
{
|
||||||
/** @var Tenancy */
|
public function __construct(
|
||||||
public $tenancy;
|
public Tenancy $tenancy,
|
||||||
|
) {
|
||||||
public function __construct(Tenancy $tenancy)
|
|
||||||
{
|
|
||||||
$this->tenancy = $tenancy;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
9
src/Events/CreatingStorageSymlink.php
Normal file
9
src/Events/CreatingStorageSymlink.php
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Stancl\Tenancy\Events;
|
||||||
|
|
||||||
|
class CreatingStorageSymlink extends Contracts\TenantEvent
|
||||||
|
{
|
||||||
|
}
|
||||||
9
src/Events/RemovingStorageSymlink.php
Normal file
9
src/Events/RemovingStorageSymlink.php
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Stancl\Tenancy\Events;
|
||||||
|
|
||||||
|
class RemovingStorageSymlink extends Contracts\TenantEvent
|
||||||
|
{
|
||||||
|
}
|
||||||
9
src/Events/StorageSymlinkCreated.php
Normal file
9
src/Events/StorageSymlinkCreated.php
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Stancl\Tenancy\Events;
|
||||||
|
|
||||||
|
class StorageSymlinkCreated extends Contracts\TenantEvent
|
||||||
|
{
|
||||||
|
}
|
||||||
9
src/Events/StorageSymlinkRemoved.php
Normal file
9
src/Events/StorageSymlinkRemoved.php
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Stancl\Tenancy\Events;
|
||||||
|
|
||||||
|
class StorageSymlinkRemoved extends Contracts\TenantEvent
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
@ -5,7 +5,7 @@ declare(strict_types=1);
|
||||||
namespace Stancl\Tenancy\Events;
|
namespace Stancl\Tenancy\Events;
|
||||||
|
|
||||||
use Stancl\Tenancy\Contracts\Syncable;
|
use Stancl\Tenancy\Contracts\Syncable;
|
||||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||||
|
|
||||||
class SyncedResourceChangedInForeignDatabase
|
class SyncedResourceChangedInForeignDatabase
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -6,17 +6,16 @@ namespace Stancl\Tenancy\Events;
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Stancl\Tenancy\Contracts\Syncable;
|
use Stancl\Tenancy\Contracts\Syncable;
|
||||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||||
|
|
||||||
class SyncedResourceSaved
|
class SyncedResourceSaved
|
||||||
{
|
{
|
||||||
/** @var Syncable|Model */
|
public Syncable&Model $model;
|
||||||
public $model;
|
|
||||||
|
|
||||||
/** @var TenantWithDatabase|Model|null */
|
/** @var (TenantWithDatabase&Model)|null */
|
||||||
public $tenant;
|
public TenantWithDatabase|null $tenant;
|
||||||
|
|
||||||
public function __construct(Syncable $model, ?TenantWithDatabase $tenant)
|
public function __construct(Syncable $model, TenantWithDatabase|null $tenant)
|
||||||
{
|
{
|
||||||
$this->model = $model;
|
$this->model = $model;
|
||||||
$this->tenant = $tenant;
|
$this->tenant = $tenant;
|
||||||
|
|
|
||||||
|
|
@ -1,13 +0,0 @@
|
||||||
<?php
|
|
||||||
|
|
||||||
declare(strict_types=1);
|
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Exceptions;
|
|
||||||
|
|
||||||
class DatabaseManagerNotRegisteredException extends \Exception
|
|
||||||
{
|
|
||||||
public function __construct($driver)
|
|
||||||
{
|
|
||||||
parent::__construct("Database manager for driver $driver is not registered.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -8,7 +8,7 @@ use Exception;
|
||||||
|
|
||||||
class DomainOccupiedByOtherTenantException extends Exception
|
class DomainOccupiedByOtherTenantException extends Exception
|
||||||
{
|
{
|
||||||
public function __construct($domain)
|
public function __construct(string $domain)
|
||||||
{
|
{
|
||||||
parent::__construct("The $domain domain is occupied by another tenant.");
|
parent::__construct("The $domain domain is occupied by another tenant.");
|
||||||
}
|
}
|
||||||
|
|
|
||||||
15
src/Exceptions/StatefulGuardRequiredException.php
Normal file
15
src/Exceptions/StatefulGuardRequiredException.php
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Stancl\Tenancy\Exceptions;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
|
|
||||||
|
class StatefulGuardRequiredException extends Exception
|
||||||
|
{
|
||||||
|
public function __construct(string $guardName)
|
||||||
|
{
|
||||||
|
parent::__construct("Cannot use a non-stateful guard ('$guardName'). A guard implementing the Illuminate\\Contracts\\Auth\\StatefulGuard interface is required.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -8,7 +8,7 @@ use Exception;
|
||||||
|
|
||||||
class TenancyNotInitializedException extends Exception
|
class TenancyNotInitializedException extends Exception
|
||||||
{
|
{
|
||||||
public function __construct($message = '')
|
public function __construct(string $message = '')
|
||||||
{
|
{
|
||||||
parent::__construct($message ?: 'Tenancy is not initialized.');
|
parent::__construct($message ?: 'Tenancy is not initialized.');
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,28 +0,0 @@
|
||||||
<?php
|
|
||||||
|
|
||||||
declare(strict_types=1);
|
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Exceptions;
|
|
||||||
|
|
||||||
use Facade\IgnitionContracts\BaseSolution;
|
|
||||||
use Facade\IgnitionContracts\ProvidesSolution;
|
|
||||||
use Facade\IgnitionContracts\Solution;
|
|
||||||
use Stancl\Tenancy\Contracts\TenantCouldNotBeIdentifiedException;
|
|
||||||
|
|
||||||
// todo: in v4 this should be suffixed with Exception
|
|
||||||
class TenantCouldNotBeIdentifiedById extends TenantCouldNotBeIdentifiedException implements ProvidesSolution
|
|
||||||
{
|
|
||||||
public function __construct($tenant_id)
|
|
||||||
{
|
|
||||||
parent::__construct("Tenant could not be identified with tenant_id: $tenant_id");
|
|
||||||
}
|
|
||||||
|
|
||||||
public function getSolution(): Solution
|
|
||||||
{
|
|
||||||
return BaseSolution::create('Tenant could not be identified with that ID')
|
|
||||||
->setSolutionDescription('Are you sure the ID is correct and the tenant exists?')
|
|
||||||
->setDocumentationLinks([
|
|
||||||
'Initializing Tenants' => 'https://tenancyforlaravel.com/docs/v3/tenants',
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
20
src/Exceptions/TenantCouldNotBeIdentifiedByIdException.php
Normal file
20
src/Exceptions/TenantCouldNotBeIdentifiedByIdException.php
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
// todo perhaps create Identification namespace
|
||||||
|
|
||||||
|
namespace Stancl\Tenancy\Exceptions;
|
||||||
|
|
||||||
|
use Stancl\Tenancy\Contracts\TenantCouldNotBeIdentifiedException;
|
||||||
|
|
||||||
|
class TenantCouldNotBeIdentifiedByIdException extends TenantCouldNotBeIdentifiedException
|
||||||
|
{
|
||||||
|
public function __construct(int|string $tenant_id)
|
||||||
|
{
|
||||||
|
$this
|
||||||
|
->tenantCouldNotBeIdentified("by tenant id: $tenant_id")
|
||||||
|
->title('Tenant could not be identified with that ID')
|
||||||
|
->description('Are you sure the ID is correct and the tenant exists?');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -4,24 +4,15 @@ declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Exceptions;
|
namespace Stancl\Tenancy\Exceptions;
|
||||||
|
|
||||||
use Facade\IgnitionContracts\BaseSolution;
|
|
||||||
use Facade\IgnitionContracts\ProvidesSolution;
|
|
||||||
use Facade\IgnitionContracts\Solution;
|
|
||||||
use Stancl\Tenancy\Contracts\TenantCouldNotBeIdentifiedException;
|
use Stancl\Tenancy\Contracts\TenantCouldNotBeIdentifiedException;
|
||||||
|
|
||||||
class TenantCouldNotBeIdentifiedByPathException extends TenantCouldNotBeIdentifiedException implements ProvidesSolution
|
class TenantCouldNotBeIdentifiedByPathException extends TenantCouldNotBeIdentifiedException
|
||||||
{
|
{
|
||||||
public function __construct($tenant_id)
|
public function __construct(int|string $tenant_id)
|
||||||
{
|
{
|
||||||
parent::__construct("Tenant could not be identified on path with tenant_id: $tenant_id");
|
$this
|
||||||
}
|
->tenantCouldNotBeIdentified("on path with tenant id: $tenant_id")
|
||||||
|
->title('Tenant could not be identified on this path')
|
||||||
public function getSolution(): Solution
|
->description('Did you forget to create a tenant for this path?');
|
||||||
{
|
|
||||||
return BaseSolution::create('Tenant could not be identified on this path')
|
|
||||||
->setSolutionDescription('Did you forget to create a tenant for this path?')
|
|
||||||
->setDocumentationLinks([
|
|
||||||
'Creating Tenants' => 'https://tenancyforlaravel.com/docs/v3/tenants/',
|
|
||||||
]);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,24 +4,15 @@ declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Exceptions;
|
namespace Stancl\Tenancy\Exceptions;
|
||||||
|
|
||||||
use Facade\IgnitionContracts\BaseSolution;
|
|
||||||
use Facade\IgnitionContracts\ProvidesSolution;
|
|
||||||
use Facade\IgnitionContracts\Solution;
|
|
||||||
use Stancl\Tenancy\Contracts\TenantCouldNotBeIdentifiedException;
|
use Stancl\Tenancy\Contracts\TenantCouldNotBeIdentifiedException;
|
||||||
|
|
||||||
class TenantCouldNotBeIdentifiedByRequestDataException extends TenantCouldNotBeIdentifiedException implements ProvidesSolution
|
class TenantCouldNotBeIdentifiedByRequestDataException extends TenantCouldNotBeIdentifiedException
|
||||||
{
|
{
|
||||||
public function __construct($tenant_id)
|
public function __construct(mixed $payload)
|
||||||
{
|
{
|
||||||
parent::__construct("Tenant could not be identified by request data with payload: $tenant_id");
|
$this
|
||||||
}
|
->tenantCouldNotBeIdentified("by request data with payload: $payload")
|
||||||
|
->title('Tenant could not be identified using this request data')
|
||||||
public function getSolution(): Solution
|
->description('Did you forget to create a tenant with this id?');
|
||||||
{
|
|
||||||
return BaseSolution::create('Tenant could not be identified with this request data')
|
|
||||||
->setSolutionDescription('Did you forget to create a tenant with this id?')
|
|
||||||
->setDocumentationLinks([
|
|
||||||
'Creating Tenants' => 'https://tenancyforlaravel.com/docs/v3/tenants/',
|
|
||||||
]);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,24 +4,15 @@ declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Exceptions;
|
namespace Stancl\Tenancy\Exceptions;
|
||||||
|
|
||||||
use Facade\IgnitionContracts\BaseSolution;
|
|
||||||
use Facade\IgnitionContracts\ProvidesSolution;
|
|
||||||
use Facade\IgnitionContracts\Solution;
|
|
||||||
use Stancl\Tenancy\Contracts\TenantCouldNotBeIdentifiedException;
|
use Stancl\Tenancy\Contracts\TenantCouldNotBeIdentifiedException;
|
||||||
|
|
||||||
class TenantCouldNotBeIdentifiedOnDomainException extends TenantCouldNotBeIdentifiedException implements ProvidesSolution
|
class TenantCouldNotBeIdentifiedOnDomainException extends TenantCouldNotBeIdentifiedException
|
||||||
{
|
{
|
||||||
public function __construct($domain)
|
public function __construct(string $domain)
|
||||||
{
|
{
|
||||||
parent::__construct("Tenant could not be identified on domain $domain");
|
$this
|
||||||
}
|
->tenantCouldNotBeIdentified("on domain $domain")
|
||||||
|
->title('Tenant could not be identified on this domain')
|
||||||
public function getSolution(): Solution
|
->description('Did you forget to create a tenant for this domain?');
|
||||||
{
|
|
||||||
return BaseSolution::create('Tenant could not be identified on this domain')
|
|
||||||
->setSolutionDescription('Did you forget to create a tenant for this domain?')
|
|
||||||
->setDocumentationLinks([
|
|
||||||
'Creating Tenants' => 'https://tenancyforlaravel.com/docs/v3/tenants/',
|
|
||||||
]);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -14,12 +14,16 @@ class CrossDomainRedirect implements Feature
|
||||||
{
|
{
|
||||||
RedirectResponse::macro('domain', function (string $domain) {
|
RedirectResponse::macro('domain', function (string $domain) {
|
||||||
/** @var RedirectResponse $this */
|
/** @var RedirectResponse $this */
|
||||||
|
|
||||||
// replace first occurance of hostname fragment with $domain
|
|
||||||
$url = $this->getTargetUrl();
|
$url = $this->getTargetUrl();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The original hostname in the redirect response.
|
||||||
|
*
|
||||||
|
* @var string $hostname
|
||||||
|
*/
|
||||||
$hostname = parse_url($url, PHP_URL_HOST);
|
$hostname = parse_url($url, PHP_URL_HOST);
|
||||||
$position = strpos($url, $hostname);
|
|
||||||
$this->setTargetUrl(substr_replace($url, $domain, $position, strlen($hostname)));
|
$this->setTargetUrl((string) str($url)->replace($hostname, $domain));
|
||||||
|
|
||||||
return $this;
|
return $this;
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,7 @@ namespace Stancl\Tenancy\Features;
|
||||||
|
|
||||||
use Illuminate\Contracts\Config\Repository;
|
use Illuminate\Contracts\Config\Repository;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Support\Arr;
|
||||||
use Illuminate\Support\Facades\Event;
|
use Illuminate\Support\Facades\Event;
|
||||||
use Stancl\Tenancy\Contracts\Feature;
|
use Stancl\Tenancy\Contracts\Feature;
|
||||||
use Stancl\Tenancy\Contracts\Tenant;
|
use Stancl\Tenancy\Contracts\Tenant;
|
||||||
|
|
@ -18,8 +19,7 @@ class TenantConfig implements Feature
|
||||||
/** @var Repository */
|
/** @var Repository */
|
||||||
protected $config;
|
protected $config;
|
||||||
|
|
||||||
/** @var array */
|
public array $originalConfig = [];
|
||||||
public $originalConfig = [];
|
|
||||||
|
|
||||||
public static $storageToConfigMap = [
|
public static $storageToConfigMap = [
|
||||||
// 'paypal_api_key' => 'services.paypal.api_key',
|
// 'paypal_api_key' => 'services.paypal.api_key',
|
||||||
|
|
@ -45,19 +45,19 @@ class TenantConfig implements Feature
|
||||||
{
|
{
|
||||||
/** @var Tenant|Model $tenant */
|
/** @var Tenant|Model $tenant */
|
||||||
foreach (static::$storageToConfigMap as $storageKey => $configKey) {
|
foreach (static::$storageToConfigMap as $storageKey => $configKey) {
|
||||||
$override = $tenant->getAttribute($storageKey);
|
$override = Arr::get($tenant, $storageKey);
|
||||||
|
|
||||||
if (! is_null($override)) {
|
if (! is_null($override)) {
|
||||||
if (is_array($configKey)) {
|
if (is_array($configKey)) {
|
||||||
foreach ($configKey as $key) {
|
foreach ($configKey as $key) {
|
||||||
$this->originalConfig[$key] = $this->originalConfig[$key] ?? $this->config[$key];
|
$this->originalConfig[$key] = $this->originalConfig[$key] ?? $this->config->get($key);
|
||||||
|
|
||||||
$this->config[$key] = $override;
|
$this->config->set($key, $override);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
$this->originalConfig[$configKey] = $this->originalConfig[$configKey] ?? $this->config[$configKey];
|
$this->originalConfig[$configKey] = $this->originalConfig[$configKey] ?? $this->config->get($configKey);
|
||||||
|
|
||||||
$this->config[$configKey] = $override;
|
$this->config->set($configKey, $override);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -66,7 +66,7 @@ class TenantConfig implements Feature
|
||||||
public function unsetTenantConfig(): void
|
public function unsetTenantConfig(): void
|
||||||
{
|
{
|
||||||
foreach ($this->originalConfig as $key => $value) {
|
foreach ($this->originalConfig as $key => $value) {
|
||||||
$this->config[$key] = $value;
|
$this->config->set($key, $value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -13,9 +13,10 @@ use Stancl\Tenancy\Tenancy;
|
||||||
|
|
||||||
class UniversalRoutes implements Feature
|
class UniversalRoutes implements Feature
|
||||||
{
|
{
|
||||||
public static $middlewareGroup = 'universal';
|
public static string $middlewareGroup = 'universal';
|
||||||
|
|
||||||
public static $identificationMiddlewares = [
|
// todo docblock
|
||||||
|
public static array $identificationMiddlewares = [
|
||||||
Middleware\InitializeTenancyByDomain::class,
|
Middleware\InitializeTenancyByDomain::class,
|
||||||
Middleware\InitializeTenancyBySubdomain::class,
|
Middleware\InitializeTenancyBySubdomain::class,
|
||||||
];
|
];
|
||||||
|
|
@ -39,7 +40,7 @@ class UniversalRoutes implements Feature
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function routeHasMiddleware(Route $route, $middleware): bool
|
public static function routeHasMiddleware(Route $route, string $middleware): bool
|
||||||
{
|
{
|
||||||
if (in_array($middleware, $route->middleware(), true)) {
|
if (in_array($middleware, $route->middleware(), true)) {
|
||||||
return true;
|
return true;
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,6 @@ declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Features;
|
namespace Stancl\Tenancy\Features;
|
||||||
|
|
||||||
use Carbon\Carbon;
|
|
||||||
use Illuminate\Http\RedirectResponse;
|
use Illuminate\Http\RedirectResponse;
|
||||||
use Illuminate\Support\Facades\Auth;
|
use Illuminate\Support\Facades\Auth;
|
||||||
use Stancl\Tenancy\Contracts\Feature;
|
use Stancl\Tenancy\Contracts\Feature;
|
||||||
|
|
@ -14,7 +13,8 @@ use Stancl\Tenancy\Tenancy;
|
||||||
|
|
||||||
class UserImpersonation implements Feature
|
class UserImpersonation implements Feature
|
||||||
{
|
{
|
||||||
public static $ttl = 60; // seconds
|
/** The lifespan of impersonation tokens (in seconds). */
|
||||||
|
public static int $ttl = 60;
|
||||||
|
|
||||||
public function bootstrap(Tenancy $tenancy): void
|
public function bootstrap(Tenancy $tenancy): void
|
||||||
{
|
{
|
||||||
|
|
@ -28,25 +28,21 @@ class UserImpersonation implements Feature
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Impersonate a user and get an HTTP redirect response. */
|
||||||
* Impersonate a user and get an HTTP redirect response.
|
public static function makeResponse(string|ImpersonationToken $token, int $ttl = null): RedirectResponse
|
||||||
*
|
|
||||||
* @param string|ImpersonationToken $token
|
|
||||||
* @param int $ttl
|
|
||||||
*/
|
|
||||||
public static function makeResponse($token, int $ttl = null): RedirectResponse
|
|
||||||
{
|
{
|
||||||
|
/** @var ImpersonationToken $token */
|
||||||
$token = $token instanceof ImpersonationToken ? $token : ImpersonationToken::findOrFail($token);
|
$token = $token instanceof ImpersonationToken ? $token : ImpersonationToken::findOrFail($token);
|
||||||
|
$ttl ??= static::$ttl;
|
||||||
|
|
||||||
if (((string) $token->tenant_id) !== ((string) tenant()->getTenantKey())) {
|
$tokenExpired = $token->created_at->diffInSeconds(now()) > $ttl;
|
||||||
abort(403);
|
|
||||||
}
|
|
||||||
|
|
||||||
$ttl = $ttl ?? static::$ttl;
|
abort_if($tokenExpired, 403);
|
||||||
|
|
||||||
if ($token->created_at->diffInSeconds(Carbon::now()) > $ttl) {
|
$tokenTenantId = (string) $token->tenant_id;
|
||||||
abort(403);
|
$currentTenantId = (string) tenant()->getTenantKey();
|
||||||
}
|
|
||||||
|
abort_unless($tokenTenantId === $currentTenantId, 403);
|
||||||
|
|
||||||
Auth::guard($token->auth_guard)->loginUsingId($token->user_id);
|
Auth::guard($token->auth_guard)->loginUsingId($token->user_id);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Foundation\Bus\Dispatchable;
|
use Illuminate\Foundation\Bus\Dispatchable;
|
||||||
use Illuminate\Queue\InteractsWithQueue;
|
use Illuminate\Queue\InteractsWithQueue;
|
||||||
use Illuminate\Queue\SerializesModels;
|
use Illuminate\Queue\SerializesModels;
|
||||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||||
use Stancl\Tenancy\Database\DatabaseManager;
|
use Stancl\Tenancy\Database\DatabaseManager;
|
||||||
use Stancl\Tenancy\Events\CreatingDatabase;
|
use Stancl\Tenancy\Events\CreatingDatabase;
|
||||||
use Stancl\Tenancy\Events\DatabaseCreated;
|
use Stancl\Tenancy\Events\DatabaseCreated;
|
||||||
|
|
@ -19,15 +19,12 @@ class CreateDatabase implements ShouldQueue
|
||||||
{
|
{
|
||||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||||
|
|
||||||
/** @var TenantWithDatabase|Model */
|
public function __construct(
|
||||||
protected $tenant;
|
protected TenantWithDatabase&Model $tenant,
|
||||||
|
) {
|
||||||
public function __construct(TenantWithDatabase $tenant)
|
|
||||||
{
|
|
||||||
$this->tenant = $tenant;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function handle(DatabaseManager $databaseManager)
|
public function handle(DatabaseManager $databaseManager): bool
|
||||||
{
|
{
|
||||||
event(new CreatingDatabase($this->tenant));
|
event(new CreatingDatabase($this->tenant));
|
||||||
|
|
||||||
|
|
@ -41,5 +38,7 @@ class CreateDatabase implements ShouldQueue
|
||||||
$this->tenant->database()->manager()->createDatabase($this->tenant);
|
$this->tenant->database()->manager()->createDatabase($this->tenant);
|
||||||
|
|
||||||
event(new DatabaseCreated($this->tenant));
|
event(new DatabaseCreated($this->tenant));
|
||||||
|
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
27
src/Jobs/CreateStorageSymlinks.php
Normal file
27
src/Jobs/CreateStorageSymlinks.php
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Stancl\Tenancy\Jobs;
|
||||||
|
|
||||||
|
use Illuminate\Bus\Queueable;
|
||||||
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||||
|
use Illuminate\Foundation\Bus\Dispatchable;
|
||||||
|
use Illuminate\Queue\InteractsWithQueue;
|
||||||
|
use Illuminate\Queue\SerializesModels;
|
||||||
|
use Stancl\Tenancy\Actions\CreateStorageSymlinksAction;
|
||||||
|
use Stancl\Tenancy\Contracts\Tenant;
|
||||||
|
|
||||||
|
class CreateStorageSymlinks implements ShouldQueue
|
||||||
|
{
|
||||||
|
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
public Tenant $tenant,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function handle(): void
|
||||||
|
{
|
||||||
|
CreateStorageSymlinksAction::handle($this->tenant);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -6,10 +6,11 @@ namespace Stancl\Tenancy\Jobs;
|
||||||
|
|
||||||
use Illuminate\Bus\Queueable;
|
use Illuminate\Bus\Queueable;
|
||||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Foundation\Bus\Dispatchable;
|
use Illuminate\Foundation\Bus\Dispatchable;
|
||||||
use Illuminate\Queue\InteractsWithQueue;
|
use Illuminate\Queue\InteractsWithQueue;
|
||||||
use Illuminate\Queue\SerializesModels;
|
use Illuminate\Queue\SerializesModels;
|
||||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||||
use Stancl\Tenancy\Events\DatabaseDeleted;
|
use Stancl\Tenancy\Events\DatabaseDeleted;
|
||||||
use Stancl\Tenancy\Events\DeletingDatabase;
|
use Stancl\Tenancy\Events\DeletingDatabase;
|
||||||
|
|
||||||
|
|
@ -17,15 +18,12 @@ class DeleteDatabase implements ShouldQueue
|
||||||
{
|
{
|
||||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||||
|
|
||||||
/** @var TenantWithDatabase */
|
public function __construct(
|
||||||
protected $tenant;
|
protected TenantWithDatabase&Model $tenant,
|
||||||
|
) {
|
||||||
public function __construct(TenantWithDatabase $tenant)
|
|
||||||
{
|
|
||||||
$this->tenant = $tenant;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function handle()
|
public function handle(): void
|
||||||
{
|
{
|
||||||
event(new DeletingDatabase($this->tenant));
|
event(new DeletingDatabase($this->tenant));
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -5,24 +5,24 @@ declare(strict_types=1);
|
||||||
namespace Stancl\Tenancy\Jobs;
|
namespace Stancl\Tenancy\Jobs;
|
||||||
|
|
||||||
use Illuminate\Bus\Queueable;
|
use Illuminate\Bus\Queueable;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Foundation\Bus\Dispatchable;
|
use Illuminate\Foundation\Bus\Dispatchable;
|
||||||
use Illuminate\Queue\InteractsWithQueue;
|
use Illuminate\Queue\InteractsWithQueue;
|
||||||
use Illuminate\Queue\SerializesModels;
|
use Illuminate\Queue\SerializesModels;
|
||||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||||
|
|
||||||
class DeleteDomains
|
class DeleteDomains
|
||||||
{
|
{
|
||||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||||
|
|
||||||
/** @var TenantWithDatabase */
|
protected TenantWithDatabase&Model $tenant;
|
||||||
protected $tenant;
|
|
||||||
|
|
||||||
public function __construct(TenantWithDatabase $tenant)
|
public function __construct(TenantWithDatabase&Model $tenant)
|
||||||
{
|
{
|
||||||
$this->tenant = $tenant;
|
$this->tenant = $tenant;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function handle()
|
public function handle(): void
|
||||||
{
|
{
|
||||||
$this->tenant->domains->each->delete();
|
$this->tenant->domains->each->delete();
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -6,30 +6,23 @@ namespace Stancl\Tenancy\Jobs;
|
||||||
|
|
||||||
use Illuminate\Bus\Queueable;
|
use Illuminate\Bus\Queueable;
|
||||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Foundation\Bus\Dispatchable;
|
use Illuminate\Foundation\Bus\Dispatchable;
|
||||||
use Illuminate\Queue\InteractsWithQueue;
|
use Illuminate\Queue\InteractsWithQueue;
|
||||||
use Illuminate\Queue\SerializesModels;
|
use Illuminate\Queue\SerializesModels;
|
||||||
use Illuminate\Support\Facades\Artisan;
|
use Illuminate\Support\Facades\Artisan;
|
||||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||||
|
|
||||||
class MigrateDatabase implements ShouldQueue
|
class MigrateDatabase implements ShouldQueue
|
||||||
{
|
{
|
||||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||||
|
|
||||||
/** @var TenantWithDatabase */
|
public function __construct(
|
||||||
protected $tenant;
|
protected TenantWithDatabase&Model $tenant,
|
||||||
|
) {
|
||||||
public function __construct(TenantWithDatabase $tenant)
|
|
||||||
{
|
|
||||||
$this->tenant = $tenant;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
public function handle(): void
|
||||||
* Execute the job.
|
|
||||||
*
|
|
||||||
* @return void
|
|
||||||
*/
|
|
||||||
public function handle()
|
|
||||||
{
|
{
|
||||||
Artisan::call('tenants:migrate', [
|
Artisan::call('tenants:migrate', [
|
||||||
'--tenants' => [$this->tenant->getTenantKey()],
|
'--tenants' => [$this->tenant->getTenantKey()],
|
||||||
|
|
|
||||||
40
src/Jobs/RemoveStorageSymlinks.php
Normal file
40
src/Jobs/RemoveStorageSymlinks.php
Normal file
|
|
@ -0,0 +1,40 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Stancl\Tenancy\Jobs;
|
||||||
|
|
||||||
|
use Illuminate\Bus\Queueable;
|
||||||
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||||
|
use Illuminate\Foundation\Bus\Dispatchable;
|
||||||
|
use Illuminate\Queue\InteractsWithQueue;
|
||||||
|
use Illuminate\Queue\SerializesModels;
|
||||||
|
use Stancl\Tenancy\Actions\RemoveStorageSymlinksAction;
|
||||||
|
use Stancl\Tenancy\Contracts\Tenant;
|
||||||
|
|
||||||
|
class RemoveStorageSymlinks implements ShouldQueue
|
||||||
|
{
|
||||||
|
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||||
|
|
||||||
|
public Tenant $tenant;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new job instance.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function __construct(Tenant $tenant)
|
||||||
|
{
|
||||||
|
$this->tenant = $tenant;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the job.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function handle()
|
||||||
|
{
|
||||||
|
RemoveStorageSymlinksAction::handle($this->tenant);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -6,30 +6,23 @@ namespace Stancl\Tenancy\Jobs;
|
||||||
|
|
||||||
use Illuminate\Bus\Queueable;
|
use Illuminate\Bus\Queueable;
|
||||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Foundation\Bus\Dispatchable;
|
use Illuminate\Foundation\Bus\Dispatchable;
|
||||||
use Illuminate\Queue\InteractsWithQueue;
|
use Illuminate\Queue\InteractsWithQueue;
|
||||||
use Illuminate\Queue\SerializesModels;
|
use Illuminate\Queue\SerializesModels;
|
||||||
use Illuminate\Support\Facades\Artisan;
|
use Illuminate\Support\Facades\Artisan;
|
||||||
use Stancl\Tenancy\Contracts\TenantWithDatabase;
|
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
|
||||||
|
|
||||||
class SeedDatabase implements ShouldQueue
|
class SeedDatabase implements ShouldQueue
|
||||||
{
|
{
|
||||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||||
|
|
||||||
/** @var TenantWithDatabase */
|
public function __construct(
|
||||||
protected $tenant;
|
protected TenantWithDatabase&Model $tenant,
|
||||||
|
) {
|
||||||
public function __construct(TenantWithDatabase $tenant)
|
|
||||||
{
|
|
||||||
$this->tenant = $tenant;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
public function handle(): void
|
||||||
* Execute the job.
|
|
||||||
*
|
|
||||||
* @return void
|
|
||||||
*/
|
|
||||||
public function handle()
|
|
||||||
{
|
{
|
||||||
Artisan::call('tenants:seed', [
|
Artisan::call('tenants:seed', [
|
||||||
'--tenants' => [$this->tenant->getTenantKey()],
|
'--tenants' => [$this->tenant->getTenantKey()],
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ use Stancl\Tenancy\Events\TenancyInitialized;
|
||||||
|
|
||||||
class BootstrapTenancy
|
class BootstrapTenancy
|
||||||
{
|
{
|
||||||
public function handle(TenancyInitialized $event)
|
public function handle(TenancyInitialized $event): void
|
||||||
{
|
{
|
||||||
event(new BootstrappingTenancy($event->tenancy));
|
event(new BootstrappingTenancy($event->tenancy));
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -17,7 +17,7 @@ class CreateTenantConnection
|
||||||
$this->database = $database;
|
$this->database = $database;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function handle(TenantEvent $event)
|
public function handle(TenantEvent $event): void
|
||||||
{
|
{
|
||||||
$this->database->createTenantConnection($event->tenant);
|
$this->database->createTenantConnection($event->tenant);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue