mirror of
https://github.com/archtechx/tenancy.git
synced 2026-02-05 16:34:04 +00:00
Merge branch '3.x' into 3.x
This commit is contained in:
commit
cbfefc6b20
25 changed files with 398 additions and 88 deletions
21
.github/ISSUE_TEMPLATE/bug-report.md
vendored
21
.github/ISSUE_TEMPLATE/bug-report.md
vendored
|
|
@ -1,21 +0,0 @@
|
||||||
---
|
|
||||||
name: "\U0001F41B Bug Report"
|
|
||||||
about: Report unexpected behavior with stancl/tenancy.
|
|
||||||
title: ''
|
|
||||||
labels: bug
|
|
||||||
assignees: stancl
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
#### Describe the bug
|
|
||||||
<!-- A clear and concise description of what the bug is. -->
|
|
||||||
|
|
||||||
#### Steps to reproduce
|
|
||||||
|
|
||||||
|
|
||||||
#### Expected behavior
|
|
||||||
A clear and concise description of what you expected to happen.
|
|
||||||
|
|
||||||
#### Your setup
|
|
||||||
- Laravel version: [e.g. 8.2.0]
|
|
||||||
- stancl/tenancy version: [e.g. 3.1.0]
|
|
||||||
48
.github/ISSUE_TEMPLATE/bug-report.yml
vendored
Normal file
48
.github/ISSUE_TEMPLATE/bug-report.yml
vendored
Normal file
|
|
@ -0,0 +1,48 @@
|
||||||
|
name: 🐛 Bug Report
|
||||||
|
description: Report unexpected behavior with stancl/tenancy.
|
||||||
|
labels: ["bug"]
|
||||||
|
assignees:
|
||||||
|
- stancl
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
Before opening a bug report, please search for the behaviour in the existing issues.
|
||||||
|
---
|
||||||
|
Thank you for taking the time to file a bug report. To address this bug as fast as possible, we need some information.
|
||||||
|
- type: textarea
|
||||||
|
id: bug-description
|
||||||
|
attributes:
|
||||||
|
label: Bug description
|
||||||
|
description: A clear and concise description of what the bug is.
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: steps
|
||||||
|
attributes:
|
||||||
|
label: Steps to reproduce
|
||||||
|
description: Step-by-step guide for reproducing the bug in a fresh Laravel application.
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
id: logs
|
||||||
|
attributes:
|
||||||
|
label: Expected behavior
|
||||||
|
description: A clear and concise description of what you expected to happen.
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: input
|
||||||
|
id: laravel-version
|
||||||
|
attributes:
|
||||||
|
label: Laravel version
|
||||||
|
placeholder: "e.g. 8.2.0"
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: input
|
||||||
|
id: tenancy-version
|
||||||
|
attributes:
|
||||||
|
label: stancl/tenancy version
|
||||||
|
placeholder: "e.g. 3.1.0"
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
4
.github/workflows/ci.yml
vendored
4
.github/workflows/ci.yml
vendored
|
|
@ -26,7 +26,3 @@ jobs:
|
||||||
run: docker-compose exec -T test composer require --no-interaction "laravel/framework:${{ matrix.laravel }}"
|
run: docker-compose exec -T test composer require --no-interaction "laravel/framework:${{ matrix.laravel }}"
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
run: ./test
|
run: ./test
|
||||||
- name: Send code coverage to codecov
|
|
||||||
env:
|
|
||||||
CODECOV_TOKEN: 24382d15-84e7-4a55-bea4-c4df96a24a9b
|
|
||||||
run: bash <(curl -s https://codecov.io/bash)
|
|
||||||
|
|
|
||||||
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -8,3 +8,4 @@ psysh
|
||||||
phpunit_var_*.xml
|
phpunit_var_*.xml
|
||||||
coverage/
|
coverage/
|
||||||
clover.xml
|
clover.xml
|
||||||
|
tests/Etc/tmp/queuetest.json
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,6 @@
|
||||||
<a href="https://laravel.com"><img alt="Laravel 6.x/7.x/8.x" src="https://img.shields.io/badge/laravel-6.x/7.x/8.x-red.svg"></a>
|
<a href="https://laravel.com"><img alt="Laravel 6.x/7.x/8.x" src="https://img.shields.io/badge/laravel-6.x/7.x/8.x-red.svg"></a>
|
||||||
<a href="https://packagist.org/packages/stancl/tenancy"><img alt="Latest Stable Version" src="https://poser.pugx.org/stancl/tenancy/version"></a>
|
<a href="https://packagist.org/packages/stancl/tenancy"><img alt="Latest Stable Version" src="https://poser.pugx.org/stancl/tenancy/version"></a>
|
||||||
<a href="https://github.com/stancl/tenancy/actions"><img alt="GitHub Actions CI status" src="https://github.com/stancl/tenancy/workflows/CI/badge.svg"></a>
|
<a href="https://github.com/stancl/tenancy/actions"><img alt="GitHub Actions CI status" src="https://github.com/stancl/tenancy/workflows/CI/badge.svg"></a>
|
||||||
<a href="https://codecov.io/gh/stancl/tenancy"><img alt="codecov" src="https://codecov.io/gh/stancl/tenancy/branch/3.x/graph/badge.svg"></a>
|
|
||||||
<a href="https://github.com/stancl/tenancy/blob/3.x/DONATIONS.md"><img alt="Donate" src="https://img.shields.io/badge/Donate-%3C3-red"></a>
|
<a href="https://github.com/stancl/tenancy/blob/3.x/DONATIONS.md"><img alt="Donate" src="https://img.shields.io/badge/Donate-%3C3-red"></a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -42,7 +42,8 @@ return [
|
||||||
'central_connection' => env('DB_CONNECTION', 'central'),
|
'central_connection' => env('DB_CONNECTION', 'central'),
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Connection used as a "template" for the tenant database connection.
|
* Connection used as a "template" for the dynamically created tenant database connection.
|
||||||
|
* Note: don't name your template connection tenant. That name is reserved by package.
|
||||||
*/
|
*/
|
||||||
'template_tenant_connection' => null,
|
'template_tenant_connection' => null,
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -18,7 +18,6 @@
|
||||||
"stancl/virtualcolumn": "^1.0"
|
"stancl/virtualcolumn": "^1.0"
|
||||||
},
|
},
|
||||||
"require-dev": {
|
"require-dev": {
|
||||||
"vlucas/phpdotenv": "^3.3|^4.0|^5.0",
|
|
||||||
"laravel/framework": "^6.0|^7.0|^8.0",
|
"laravel/framework": "^6.0|^7.0|^8.0",
|
||||||
"orchestra/testbench-browser-kit": "^4.0|^5.0|^6.0",
|
"orchestra/testbench-browser-kit": "^4.0|^5.0|^6.0",
|
||||||
"league/flysystem-aws-s3-v3": "~1.0",
|
"league/flysystem-aws-s3-v3": "~1.0",
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ services:
|
||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
args:
|
args:
|
||||||
PHP_VERSION: ${PHP_VERSION}
|
PHP_VERSION: ${PHP_VERSION:-8.1}
|
||||||
depends_on:
|
depends_on:
|
||||||
mysql:
|
mysql:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
|
|
|
||||||
|
|
@ -6,6 +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\DatabaseManager;
|
use Stancl\Tenancy\Database\DatabaseManager;
|
||||||
use Stancl\Tenancy\Exceptions\TenantDatabaseDoesNotExistException;
|
use Stancl\Tenancy\Exceptions\TenantDatabaseDoesNotExistException;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,14 +4,18 @@ declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Bootstrappers;
|
namespace Stancl\Tenancy\Bootstrappers;
|
||||||
|
|
||||||
|
use Illuminate\Support\Str;
|
||||||
use Illuminate\Config\Repository;
|
use Illuminate\Config\Repository;
|
||||||
use Illuminate\Contracts\Events\Dispatcher;
|
|
||||||
use Illuminate\Contracts\Foundation\Application;
|
|
||||||
use Illuminate\Queue\Events\JobProcessing;
|
|
||||||
use Illuminate\Queue\QueueManager;
|
use Illuminate\Queue\QueueManager;
|
||||||
use Illuminate\Support\Testing\Fakes\QueueFake;
|
|
||||||
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
|
|
||||||
use Stancl\Tenancy\Contracts\Tenant;
|
use Stancl\Tenancy\Contracts\Tenant;
|
||||||
|
use Illuminate\Queue\Events\JobFailed;
|
||||||
|
use Illuminate\Queue\Events\JobProcessed;
|
||||||
|
use Illuminate\Queue\Events\JobProcessing;
|
||||||
|
use Illuminate\Contracts\Events\Dispatcher;
|
||||||
|
use Illuminate\Queue\Events\JobRetryRequested;
|
||||||
|
use Illuminate\Support\Testing\Fakes\QueueFake;
|
||||||
|
use Illuminate\Contracts\Foundation\Application;
|
||||||
|
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
|
||||||
|
|
||||||
class QueueTenancyBootstrapper implements TenancyBootstrapper
|
class QueueTenancyBootstrapper implements TenancyBootstrapper
|
||||||
{
|
{
|
||||||
|
|
@ -21,6 +25,14 @@ class QueueTenancyBootstrapper implements TenancyBootstrapper
|
||||||
/** @var QueueManager */
|
/** @var QueueManager */
|
||||||
protected $queue;
|
protected $queue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Don't persist the same tenant across multiple jobs even if they have the same tenant ID.
|
||||||
|
*
|
||||||
|
* This is useful when you're changing the tenant's state (e.g. properties in the `data` column) and want the next job to initialize tenancy again
|
||||||
|
* with the new data. Features like the Tenant Config are only executed when tenancy is initialized, so the re-initialization is needed in some cases.
|
||||||
|
*/
|
||||||
|
public static bool $forceRefresh = false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The normal constructor is only executed after tenancy is bootstrapped.
|
* The normal constructor is only executed after tenancy is bootstrapped.
|
||||||
* However, we're registering a hook to initialize tenancy. Therefore,
|
* However, we're registering a hook to initialize tenancy. Therefore,
|
||||||
|
|
@ -28,7 +40,7 @@ class QueueTenancyBootstrapper implements TenancyBootstrapper
|
||||||
*/
|
*/
|
||||||
public static function __constructStatic(Application $app)
|
public static function __constructStatic(Application $app)
|
||||||
{
|
{
|
||||||
static::setUpJobListener($app->make(Dispatcher::class));
|
static::setUpJobListener($app->make(Dispatcher::class), $app->runningUnitTests());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function __construct(Repository $config, QueueManager $queue)
|
public function __construct(Repository $config, QueueManager $queue)
|
||||||
|
|
@ -39,25 +51,90 @@ class QueueTenancyBootstrapper implements TenancyBootstrapper
|
||||||
$this->setUpPayloadGenerator();
|
$this->setUpPayloadGenerator();
|
||||||
}
|
}
|
||||||
|
|
||||||
protected static function setUpJobListener($dispatcher)
|
protected static function setUpJobListener($dispatcher, $runningTests)
|
||||||
{
|
{
|
||||||
$dispatcher->listen(JobProcessing::class, function ($event) {
|
$previousTenant = null;
|
||||||
$tenantId = $event->job->payload()['tenant_id'] ?? null;
|
|
||||||
|
|
||||||
// The job is not tenant-aware
|
$dispatcher->listen(JobProcessing::class, function ($event) use (&$previousTenant) {
|
||||||
if (! $tenantId) {
|
$previousTenant = tenant();
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Tenancy is already initialized for the tenant (e.g. dispatchNow was used)
|
static::initializeTenancyForQueue($event->job->payload()['tenant_id'] ?? null);
|
||||||
if (tenancy()->initialized && tenant()->getTenantKey() === $tenantId) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Tenancy was either not initialized, or initialized for a different tenant.
|
|
||||||
// Therefore, we initialize it for the correct tenant.
|
|
||||||
tenancy()->initialize(tenancy()->find($tenantId));
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (Str::startsWith(app()->version(), '8')) {
|
||||||
|
// JobRetryRequested only exists since Laravel 8
|
||||||
|
$dispatcher->listen(JobRetryRequested::class, function ($event) use (&$previousTenant) {
|
||||||
|
$previousTenant = tenant();
|
||||||
|
|
||||||
|
static::initializeTenancyForQueue($event->payload()['tenant_id'] ?? null);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we're running tests, we make sure to clean up after any artisan('queue:work') calls
|
||||||
|
$revertToPreviousState = function ($event) use (&$previousTenant, $runningTests) {
|
||||||
|
if ($runningTests) {
|
||||||
|
static::revertToPreviousState($event, $previousTenant);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
$dispatcher->listen(JobProcessed::class, $revertToPreviousState); // artisan('queue:work') which succeeds
|
||||||
|
$dispatcher->listen(JobFailed::class, $revertToPreviousState); // artisan('queue:work') which fails
|
||||||
|
}
|
||||||
|
|
||||||
|
protected static function initializeTenancyForQueue($tenantId)
|
||||||
|
{
|
||||||
|
if (! $tenantId) {
|
||||||
|
// The job is not tenant-aware
|
||||||
|
if (tenancy()->initialized) {
|
||||||
|
// Tenancy was initialized, so we revert back to the central context
|
||||||
|
tenancy()->end();
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (static::$forceRefresh) {
|
||||||
|
// Re-initialize tenancy between all jobs
|
||||||
|
if (tenancy()->initialized) {
|
||||||
|
tenancy()->end();
|
||||||
|
}
|
||||||
|
|
||||||
|
tenancy()->initialize(tenancy()->find($tenantId));
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tenancy()->initialized) {
|
||||||
|
// Tenancy is already initialized
|
||||||
|
if (tenant()->getTenantKey() === $tenantId) {
|
||||||
|
// It's initialized for the same tenant (e.g. dispatchNow was used, or the previous job also ran for this tenant)
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tenancy was either not initialized, or initialized for a different tenant.
|
||||||
|
// Therefore, we initialize it for the correct tenant.
|
||||||
|
tenancy()->initialize(tenancy()->find($tenantId));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected static function revertToPreviousState($event, &$previousTenant)
|
||||||
|
{
|
||||||
|
$tenantId = $event->job->payload()['tenant_id'] ?? null;
|
||||||
|
|
||||||
|
// The job was not tenant-aware
|
||||||
|
if (! $tenantId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Revert back to the previous tenant
|
||||||
|
if (tenant() && $previousTenant && $previousTenant->isNot(tenant())) {
|
||||||
|
tenancy()->initialize($previousTenant);
|
||||||
|
}
|
||||||
|
|
||||||
|
// End tenancy
|
||||||
|
if (tenant() && (! $previousTenant)) {
|
||||||
|
tenancy()->end();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function setUpPayloadGenerator()
|
protected function setUpPayloadGenerator()
|
||||||
|
|
|
||||||
|
|
@ -20,8 +20,10 @@ class CacheManager extends BaseCacheManager
|
||||||
$tags = [config('tenancy.cache.tag_base') . tenant()->getTenantKey()];
|
$tags = [config('tenancy.cache.tag_base') . tenant()->getTenantKey()];
|
||||||
|
|
||||||
if ($method === 'tags') {
|
if ($method === 'tags') {
|
||||||
if (count($parameters) !== 1) {
|
$count = count($parameters);
|
||||||
throw new \Exception("Method tags() takes exactly 1 argument. {count($parameters)} passed.");
|
|
||||||
|
if ($count !== 1) {
|
||||||
|
throw new \Exception("Method tags() takes exactly 1 argument. $count passed.");
|
||||||
}
|
}
|
||||||
|
|
||||||
$names = $parameters[0];
|
$names = $parameters[0];
|
||||||
|
|
|
||||||
|
|
@ -55,7 +55,7 @@ class Migrate extends MigrateCommand
|
||||||
}
|
}
|
||||||
|
|
||||||
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
|
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
|
||||||
$this->line("Tenant: {$tenant['id']}");
|
$this->line("Tenant: {$tenant->getTenantKey()}");
|
||||||
|
|
||||||
event(new MigratingDatabase($tenant));
|
event(new MigratingDatabase($tenant));
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -53,7 +53,7 @@ class Rollback extends RollbackCommand
|
||||||
}
|
}
|
||||||
|
|
||||||
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
|
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
|
||||||
$this->line("Tenant: {$tenant['id']}");
|
$this->line("Tenant: {$tenant->getTenantKey()}");
|
||||||
|
|
||||||
event(new RollingBackDatabase($tenant));
|
event(new RollingBackDatabase($tenant));
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -33,8 +33,7 @@ class Run extends Command
|
||||||
public function handle()
|
public function handle()
|
||||||
{
|
{
|
||||||
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
|
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
|
||||||
$this->line("Tenant: {$tenant['id']}");
|
$this->line("Tenant: {$tenant->getTenantKey()}");
|
||||||
tenancy()->initialize($tenant);
|
|
||||||
|
|
||||||
$callback = function ($prefix = '') {
|
$callback = function ($prefix = '') {
|
||||||
return function ($arguments, $argument) use ($prefix) {
|
return function ($arguments, $argument) use ($prefix) {
|
||||||
|
|
|
||||||
|
|
@ -51,7 +51,7 @@ class Seed extends SeedCommand
|
||||||
}
|
}
|
||||||
|
|
||||||
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
|
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
|
||||||
$this->line("Tenant: {$tenant['id']}");
|
$this->line("Tenant: {$tenant->getTenantKey()}");
|
||||||
|
|
||||||
event(new SeedingDatabase($tenant));
|
event(new SeedingDatabase($tenant));
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -36,9 +36,9 @@ class TenantList extends Command
|
||||||
->cursor()
|
->cursor()
|
||||||
->each(function (Tenant $tenant) {
|
->each(function (Tenant $tenant) {
|
||||||
if ($tenant->domains) {
|
if ($tenant->domains) {
|
||||||
$this->line("[Tenant] id: {$tenant['id']} @ " . implode('; ', $tenant->domains->pluck('domain')->toArray() ?? []));
|
$this->line("[Tenant] {$tenant->getTenantKeyName()}: {$tenant->getTenantKey()} @ " . implode('; ', $tenant->domains->pluck('domain')->toArray() ?? []));
|
||||||
} else {
|
} else {
|
||||||
$this->line("[Tenant] id: {$tenant['id']}");
|
$this->line("[Tenant] {$tenant->getTenantKeyName()}: {$tenant->getTenantKey()}");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -38,7 +38,7 @@ class DatabaseManager
|
||||||
*/
|
*/
|
||||||
public function connectToTenant(TenantWithDatabase $tenant)
|
public function connectToTenant(TenantWithDatabase $tenant)
|
||||||
{
|
{
|
||||||
$this->database->purge('tenant');
|
$this->purgeTenantConnection();
|
||||||
$this->createTenantConnection($tenant);
|
$this->createTenantConnection($tenant);
|
||||||
$this->setDefaultConnection('tenant');
|
$this->setDefaultConnection('tenant');
|
||||||
}
|
}
|
||||||
|
|
@ -48,10 +48,7 @@ class DatabaseManager
|
||||||
*/
|
*/
|
||||||
public function reconnectToCentral()
|
public function reconnectToCentral()
|
||||||
{
|
{
|
||||||
if (tenancy()->initialized) {
|
$this->purgeTenantConnection();
|
||||||
$this->database->purge('tenant');
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->setDefaultConnection($this->config->get('tenancy.database.central_connection'));
|
$this->setDefaultConnection($this->config->get('tenancy.database.central_connection'));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -60,7 +57,7 @@ class DatabaseManager
|
||||||
*/
|
*/
|
||||||
public function setDefaultConnection(string $connection)
|
public function setDefaultConnection(string $connection)
|
||||||
{
|
{
|
||||||
$this->app['config']['database.default'] = $connection;
|
$this->config['database.default'] = $connection;
|
||||||
$this->database->setDefaultConnection($connection);
|
$this->database->setDefaultConnection($connection);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -69,7 +66,19 @@ class DatabaseManager
|
||||||
*/
|
*/
|
||||||
public function createTenantConnection(TenantWithDatabase $tenant)
|
public function createTenantConnection(TenantWithDatabase $tenant)
|
||||||
{
|
{
|
||||||
$this->app['config']['database.connections.tenant'] = $tenant->database()->connection();
|
$this->config['database.connections.tenant'] = $tenant->database()->connection();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Purge the tenant database connection.
|
||||||
|
*/
|
||||||
|
public function purgeTenantConnection()
|
||||||
|
{
|
||||||
|
if (array_key_exists('tenant', $this->database->getConnections())) {
|
||||||
|
$this->database->purge('tenant');
|
||||||
|
}
|
||||||
|
|
||||||
|
unset($this->config['database.connections.tenant']);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ use Facade\IgnitionContracts\ProvidesSolution;
|
||||||
use Facade\IgnitionContracts\Solution;
|
use Facade\IgnitionContracts\Solution;
|
||||||
use Stancl\Tenancy\Contracts\TenantCouldNotBeIdentifiedException;
|
use Stancl\Tenancy\Contracts\TenantCouldNotBeIdentifiedException;
|
||||||
|
|
||||||
// todo: in v3 this should be suffixed with Exception
|
// todo: in v4 this should be suffixed with Exception
|
||||||
class TenantCouldNotBeIdentifiedById extends TenantCouldNotBeIdentifiedException implements ProvidesSolution
|
class TenantCouldNotBeIdentifiedById extends TenantCouldNotBeIdentifiedException implements ProvidesSolution
|
||||||
{
|
{
|
||||||
public function __construct($tenant_id)
|
public function __construct($tenant_id)
|
||||||
|
|
|
||||||
|
|
@ -40,7 +40,7 @@ class UniversalRoutes implements Feature
|
||||||
}
|
}
|
||||||
|
|
||||||
// Loop one level deep and check if the route's middleware
|
// Loop one level deep and check if the route's middleware
|
||||||
// groups have the searhced middleware group inside them
|
// groups have the searched middleware group inside them
|
||||||
$middlewareGroups = Router::getMiddlewareGroups();
|
$middlewareGroups = Router::getMiddlewareGroups();
|
||||||
foreach ($route->gatherMiddleware() as $inner) {
|
foreach ($route->gatherMiddleware() as $inner) {
|
||||||
if (! $inner instanceof Closure && isset($middlewareGroups[$inner]) && in_array($middleware, $middlewareGroups[$inner], true)) {
|
if (! $inner instanceof Closure && isset($middlewareGroups[$inner]) && in_array($middleware, $middlewareGroups[$inner], true)) {
|
||||||
|
|
|
||||||
|
|
@ -66,10 +66,10 @@ class Tenancy
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
$this->initialized = false;
|
|
||||||
|
|
||||||
event(new Events\TenancyEnded($this));
|
event(new Events\TenancyEnded($this));
|
||||||
|
|
||||||
|
$this->initialized = false;
|
||||||
|
|
||||||
$this->tenant = null;
|
$this->tenant = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,7 @@ namespace Stancl\Tenancy;
|
||||||
use Illuminate\Cache\CacheManager;
|
use Illuminate\Cache\CacheManager;
|
||||||
use Illuminate\Support\ServiceProvider;
|
use Illuminate\Support\ServiceProvider;
|
||||||
use Stancl\Tenancy\Bootstrappers\FilesystemTenancyBootstrapper;
|
use Stancl\Tenancy\Bootstrappers\FilesystemTenancyBootstrapper;
|
||||||
|
use Stancl\Tenancy\Contracts\Domain;
|
||||||
use Stancl\Tenancy\Contracts\Tenant;
|
use Stancl\Tenancy\Contracts\Tenant;
|
||||||
use Stancl\Tenancy\Resolvers\DomainTenantResolver;
|
use Stancl\Tenancy\Resolvers\DomainTenantResolver;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
{"tenant_id":"The current tenant id is: acme"}
|
|
||||||
|
|
@ -4,18 +4,31 @@ declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
namespace Stancl\Tenancy\Tests;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
use Illuminate\Bus\Queueable;
|
use Illuminate\Bus\Queueable;
|
||||||
|
use Spatie\Valuestore\Valuestore;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Stancl\Tenancy\Tests\Etc\User;
|
||||||
|
use Stancl\JobPipeline\JobPipeline;
|
||||||
|
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||||
|
use Illuminate\Support\Facades\Event;
|
||||||
|
use Illuminate\Queue\SerializesModels;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
use Stancl\Tenancy\Events\TenancyEnded;
|
||||||
|
use Stancl\Tenancy\Jobs\CreateDatabase;
|
||||||
|
use Illuminate\Queue\InteractsWithQueue;
|
||||||
|
use Stancl\Tenancy\Events\TenantCreated;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Queue\Events\JobProcessed;
|
||||||
|
use Illuminate\Queue\Events\JobProcessing;
|
||||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||||
use Illuminate\Foundation\Bus\Dispatchable;
|
use Illuminate\Foundation\Bus\Dispatchable;
|
||||||
use Illuminate\Queue\Events\JobProcessing;
|
|
||||||
use Illuminate\Queue\InteractsWithQueue;
|
|
||||||
use Illuminate\Queue\SerializesModels;
|
|
||||||
use Illuminate\Support\Facades\Event;
|
|
||||||
use Spatie\Valuestore\Valuestore;
|
|
||||||
use Stancl\Tenancy\Bootstrappers\QueueTenancyBootstrapper;
|
|
||||||
use Stancl\Tenancy\Events\TenancyInitialized;
|
use Stancl\Tenancy\Events\TenancyInitialized;
|
||||||
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
||||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
||||||
|
use Stancl\Tenancy\Bootstrappers\QueueTenancyBootstrapper;
|
||||||
|
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
|
||||||
|
|
||||||
class QueueTest extends TestCase
|
class QueueTest extends TestCase
|
||||||
{
|
{
|
||||||
|
|
@ -31,15 +44,54 @@ class QueueTest extends TestCase
|
||||||
config([
|
config([
|
||||||
'tenancy.bootstrappers' => [
|
'tenancy.bootstrappers' => [
|
||||||
QueueTenancyBootstrapper::class,
|
QueueTenancyBootstrapper::class,
|
||||||
|
DatabaseTenancyBootstrapper::class,
|
||||||
],
|
],
|
||||||
'queue.default' => 'redis',
|
'queue.default' => 'redis',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||||
|
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
||||||
|
|
||||||
$this->valuestore = Valuestore::make(__DIR__ . '/Etc/tmp/queuetest.json')->flush();
|
$this->valuestore = Valuestore::make(__DIR__ . '/Etc/tmp/queuetest.json')->flush();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function tearDown(): void
|
||||||
|
{
|
||||||
|
$this->valuestore->flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function withFailedJobs()
|
||||||
|
{
|
||||||
|
Schema::connection('central')->create('failed_jobs', function (Blueprint $table) {
|
||||||
|
$table->increments('id');
|
||||||
|
$table->string('uuid')->unique();
|
||||||
|
$table->text('connection');
|
||||||
|
$table->text('queue');
|
||||||
|
$table->longText('payload');
|
||||||
|
$table->longText('exception');
|
||||||
|
$table->timestamp('failed_at')->useCurrent();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function withUsers()
|
||||||
|
{
|
||||||
|
Schema::create('users', function (Blueprint $table) {
|
||||||
|
$table->increments('id');
|
||||||
|
$table->string('name');
|
||||||
|
$table->string('email')->unique();
|
||||||
|
$table->string('password');
|
||||||
|
$table->rememberToken();
|
||||||
|
$table->timestamps();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function withTenantDatabases()
|
||||||
|
{
|
||||||
|
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
||||||
|
return $event->tenant;
|
||||||
|
})->toListener());
|
||||||
|
}
|
||||||
|
|
||||||
/** @test */
|
/** @test */
|
||||||
public function tenant_id_is_passed_to_tenant_queues()
|
public function tenant_id_is_passed_to_tenant_queues()
|
||||||
{
|
{
|
||||||
|
|
@ -49,7 +101,7 @@ class QueueTest extends TestCase
|
||||||
|
|
||||||
tenancy()->initialize($tenant);
|
tenancy()->initialize($tenant);
|
||||||
|
|
||||||
Event::fake([JobProcessing::class]);
|
Event::fake([JobProcessing::class, JobProcessed::class]);
|
||||||
|
|
||||||
dispatch(new TestJob($this->valuestore));
|
dispatch(new TestJob($this->valuestore));
|
||||||
|
|
||||||
|
|
@ -79,21 +131,95 @@ class QueueTest extends TestCase
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @test */
|
/**
|
||||||
public function tenancy_is_initialized_inside_queues()
|
* @test
|
||||||
|
*
|
||||||
|
* @testWith [true]
|
||||||
|
* [false]
|
||||||
|
*/
|
||||||
|
public function tenancy_is_initialized_inside_queues(bool $shouldEndTenancy)
|
||||||
{
|
{
|
||||||
$tenant = Tenant::create([
|
$this->withTenantDatabases();
|
||||||
'id' => 'acme',
|
$this->withFailedJobs();
|
||||||
]);
|
|
||||||
|
$tenant = Tenant::create();
|
||||||
|
|
||||||
tenancy()->initialize($tenant);
|
tenancy()->initialize($tenant);
|
||||||
|
|
||||||
dispatch(new TestJob($this->valuestore));
|
$this->withUsers();
|
||||||
|
|
||||||
|
$user = User::create(['name' => 'Foo', 'email' => 'foo@bar.com', 'password' => 'secret']);
|
||||||
|
|
||||||
|
$this->valuestore->put('userName', 'Bar');
|
||||||
|
|
||||||
|
dispatch(new TestJob($this->valuestore, $user));
|
||||||
|
|
||||||
$this->assertFalse($this->valuestore->has('tenant_id'));
|
$this->assertFalse($this->valuestore->has('tenant_id'));
|
||||||
|
|
||||||
|
if ($shouldEndTenancy) {
|
||||||
|
tenancy()->end();
|
||||||
|
}
|
||||||
|
|
||||||
$this->artisan('queue:work --once');
|
$this->artisan('queue:work --once');
|
||||||
|
|
||||||
$this->assertSame('The current tenant id is: acme', $this->valuestore->get('tenant_id'));
|
$this->assertSame(0, DB::connection('central')->table('failed_jobs')->count());
|
||||||
|
|
||||||
|
$this->assertSame('The current tenant id is: ' . $tenant->id, $this->valuestore->get('tenant_id'));
|
||||||
|
|
||||||
|
$tenant->run(function () use ($user) {
|
||||||
|
$this->assertSame('Bar', $user->fresh()->name);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @test
|
||||||
|
*
|
||||||
|
* @testWith [true]
|
||||||
|
* [false]
|
||||||
|
*/
|
||||||
|
public function tenancy_is_initialized_when_retrying_jobs(bool $shouldEndTenancy)
|
||||||
|
{
|
||||||
|
if (! Str::startsWith(app()->version(), '8')) {
|
||||||
|
$this->markTestSkipped('queue:retry tenancy is only supported in Laravel 8');
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->withFailedJobs();
|
||||||
|
$this->withTenantDatabases();
|
||||||
|
|
||||||
|
$tenant = Tenant::create();
|
||||||
|
|
||||||
|
tenancy()->initialize($tenant);
|
||||||
|
|
||||||
|
$this->withUsers();
|
||||||
|
|
||||||
|
$user = User::create(['name' => 'Foo', 'email' => 'foo@bar.com', 'password' => 'secret']);
|
||||||
|
|
||||||
|
$this->valuestore->put('userName', 'Bar');
|
||||||
|
$this->valuestore->put('shouldFail', true);
|
||||||
|
|
||||||
|
dispatch(new TestJob($this->valuestore, $user));
|
||||||
|
|
||||||
|
$this->assertFalse($this->valuestore->has('tenant_id'));
|
||||||
|
|
||||||
|
if ($shouldEndTenancy) {
|
||||||
|
tenancy()->end();
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->artisan('queue:work --once');
|
||||||
|
|
||||||
|
$this->assertSame(1, DB::connection('central')->table('failed_jobs')->count());
|
||||||
|
$this->assertNull($this->valuestore->get('tenant_id')); // job failed
|
||||||
|
|
||||||
|
$this->artisan('queue:retry all');
|
||||||
|
$this->artisan('queue:work --once');
|
||||||
|
|
||||||
|
$this->assertSame(0, DB::connection('central')->table('failed_jobs')->count());
|
||||||
|
|
||||||
|
$this->assertSame('The current tenant id is: ' . $tenant->id, $this->valuestore->get('tenant_id')); // job succeeded
|
||||||
|
|
||||||
|
$tenant->run(function () use ($user) {
|
||||||
|
$this->assertSame('Bar', $user->fresh()->name);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @test */
|
/** @test */
|
||||||
|
|
@ -127,13 +253,31 @@ class TestJob implements ShouldQueue
|
||||||
/** @var Valuestore */
|
/** @var Valuestore */
|
||||||
protected $valuestore;
|
protected $valuestore;
|
||||||
|
|
||||||
public function __construct(Valuestore $valuestore)
|
/** @var User|null */
|
||||||
|
protected $user;
|
||||||
|
|
||||||
|
public function __construct(Valuestore $valuestore, User $user = null)
|
||||||
{
|
{
|
||||||
$this->valuestore = $valuestore;
|
$this->valuestore = $valuestore;
|
||||||
|
$this->user = $user;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function handle()
|
public function handle()
|
||||||
{
|
{
|
||||||
|
if ($this->valuestore->get('shouldFail')) {
|
||||||
|
$this->valuestore->put('shouldFail', false);
|
||||||
|
|
||||||
|
throw new Exception('failing');
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->user) {
|
||||||
|
assert($this->user->getConnectionName() === 'tenant');
|
||||||
|
}
|
||||||
|
|
||||||
$this->valuestore->put('tenant_id', 'The current tenant id is: ' . tenant('id'));
|
$this->valuestore->put('tenant_id', 'The current tenant id is: ' . tenant('id'));
|
||||||
|
|
||||||
|
if ($userName = $this->valuestore->get('userName')) {
|
||||||
|
$this->user->update(['name' => $userName]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,17 +4,21 @@ declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
namespace Stancl\Tenancy\Tests;
|
||||||
|
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
use Illuminate\Support\Facades\Event;
|
use Illuminate\Support\Facades\Event;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
use PDO;
|
use PDO;
|
||||||
use Stancl\JobPipeline\JobPipeline;
|
use Stancl\JobPipeline\JobPipeline;
|
||||||
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
|
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
|
||||||
use Stancl\Tenancy\Database\DatabaseManager;
|
use Stancl\Tenancy\Database\DatabaseManager;
|
||||||
|
use Stancl\Tenancy\Events\TenancyEnded;
|
||||||
use Stancl\Tenancy\Events\TenancyInitialized;
|
use Stancl\Tenancy\Events\TenancyInitialized;
|
||||||
use Stancl\Tenancy\Events\TenantCreated;
|
use Stancl\Tenancy\Events\TenantCreated;
|
||||||
use Stancl\Tenancy\Exceptions\TenantDatabaseAlreadyExistsException;
|
use Stancl\Tenancy\Exceptions\TenantDatabaseAlreadyExistsException;
|
||||||
use Stancl\Tenancy\Jobs\CreateDatabase;
|
use Stancl\Tenancy\Jobs\CreateDatabase;
|
||||||
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
||||||
|
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
||||||
use Stancl\Tenancy\TenantDatabaseManagers\MicrosoftSQLDatabaseManager;
|
use Stancl\Tenancy\TenantDatabaseManagers\MicrosoftSQLDatabaseManager;
|
||||||
use Stancl\Tenancy\TenantDatabaseManagers\MySQLDatabaseManager;
|
use Stancl\Tenancy\TenantDatabaseManagers\MySQLDatabaseManager;
|
||||||
use Stancl\Tenancy\TenantDatabaseManagers\PermissionControlledMySQLDatabaseManager;
|
use Stancl\Tenancy\TenantDatabaseManagers\PermissionControlledMySQLDatabaseManager;
|
||||||
|
|
@ -104,6 +108,52 @@ class TenantDatabaseManagerTest extends TestCase
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** @test */
|
||||||
|
public function the_tenant_connection_is_fully_removed()
|
||||||
|
{
|
||||||
|
config([
|
||||||
|
'tenancy.boostrappers' => [
|
||||||
|
DatabaseTenancyBootstrapper::class,
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
|
||||||
|
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
||||||
|
return $event->tenant;
|
||||||
|
})->toListener());
|
||||||
|
|
||||||
|
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||||
|
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
||||||
|
|
||||||
|
$tenant = Tenant::create();
|
||||||
|
|
||||||
|
$this->assertSame(['central'], array_keys(app('db')->getConnections()));
|
||||||
|
$this->assertArrayNotHasKey('tenant', config('database.connections'));
|
||||||
|
|
||||||
|
tenancy()->initialize($tenant);
|
||||||
|
|
||||||
|
$this->createUsersTable();
|
||||||
|
|
||||||
|
$this->assertSame(['central', 'tenant'], array_keys(app('db')->getConnections()));
|
||||||
|
$this->assertArrayHasKey('tenant', config('database.connections'));
|
||||||
|
|
||||||
|
tenancy()->end();
|
||||||
|
|
||||||
|
$this->assertSame(['central'], array_keys(app('db')->getConnections()));
|
||||||
|
$this->assertNull(config('database.connections.tenant'));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function createUsersTable()
|
||||||
|
{
|
||||||
|
Schema::create('users', function (Blueprint $table) {
|
||||||
|
$table->increments('id');
|
||||||
|
$table->string('name');
|
||||||
|
$table->string('email')->unique();
|
||||||
|
$table->string('password');
|
||||||
|
$table->rememberToken();
|
||||||
|
$table->timestamps();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/** @test */
|
/** @test */
|
||||||
public function db_name_is_prefixed_with_db_path_when_sqlite_is_used()
|
public function db_name_is_prefixed_with_db_path_when_sqlite_is_used()
|
||||||
{
|
{
|
||||||
|
|
@ -219,5 +269,6 @@ class TenantDatabaseManagerTest extends TestCase
|
||||||
/** @test */
|
/** @test */
|
||||||
public function path_used_by_sqlite_manager_can_be_customized()
|
public function path_used_by_sqlite_manager_can_be_customized()
|
||||||
{
|
{
|
||||||
|
$this->markTestIncomplete();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -48,7 +48,11 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase
|
||||||
protected function getEnvironmentSetUp($app)
|
protected function getEnvironmentSetUp($app)
|
||||||
{
|
{
|
||||||
if (file_exists(__DIR__ . '/../.env')) {
|
if (file_exists(__DIR__ . '/../.env')) {
|
||||||
\Dotenv\Dotenv::create(__DIR__ . '/..')->load();
|
if (method_exists(\Dotenv\Dotenv::class, 'createImmutable')) {
|
||||||
|
\Dotenv\Dotenv::createImmutable(__DIR__ . '/..')->load();
|
||||||
|
} else {
|
||||||
|
\Dotenv\Dotenv::create(__DIR__ . '/..')->load();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$app['config']->set([
|
$app['config']->set([
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue