1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2025-12-13 23:54:03 +00:00

Merge branch 'master' into shared-users

This commit is contained in:
Samuel Štancl 2020-05-13 00:33:27 +02:00 committed by GitHub
commit 8915297c30
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
85 changed files with 880 additions and 3280 deletions

View file

@ -1,86 +0,0 @@
<?php
namespace Stancl\Tenancy\Tests\v3;
use Illuminate\Support\Facades\Event;
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
use Stancl\Tenancy\Database\Models\Tenant;
use Stancl\Tenancy\Events\Listeners\BootstrapTenancy;
use Stancl\Tenancy\Events\Listeners\RevertToCentralContext;
use Stancl\Tenancy\Events\TenancyEnded;
use Stancl\Tenancy\Events\TenancyInitialized;
use Stancl\Tenancy\Tests\TestCase;
class AutomaticModeTest extends TestCase
{
public function setUp(): void
{
parent::setUp();
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
}
/** @test */
public function context_is_switched_when_tenancy_is_initialized()
{
config(['tenancy.bootstrappers' => [
MyBootstrapper::class,
]]);
$tenant = Tenant::create([
'id' => 'acme',
]);
tenancy()->initialize($tenant);
$this->assertSame('acme', app('tenancy_initialized_for_tenant'));
}
/** @test */
public function context_is_reverted_when_tenancy_is_ended()
{
$this->context_is_switched_when_tenancy_is_initialized();
tenancy()->end();
$this->assertSame(true, app('tenancy_ended'));
}
/** @test */
public function context_is_switched_when_tenancy_is_reinitialized()
{
config(['tenancy.bootstrappers' => [
MyBootstrapper::class,
]]);
$tenant = Tenant::create([
'id' => 'acme',
]);
tenancy()->initialize($tenant);
$this->assertSame('acme', app('tenancy_initialized_for_tenant'));
$tenant2 = Tenant::create([
'id' => 'foobar',
]);
tenancy()->initialize($tenant2);
$this->assertSame('foobar', app('tenancy_initialized_for_tenant'));
}
}
class MyBootstrapper implements TenancyBootstrapper
{
public function start(\Stancl\Tenancy\Contracts\Tenant $tenant)
{
app()->instance('tenancy_initialized_for_tenant', $tenant->getTenantKey());
}
public function end()
{
app()->instance('tenancy_ended', true);
}
}

View file

@ -1,182 +0,0 @@
<?php
namespace Stancl\Tenancy\Tests\v3;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;
use Stancl\Tenancy\Database\Models\Tenant;
use Stancl\Tenancy\Events\Listeners\BootstrapTenancy;
use Stancl\Tenancy\Events\Listeners\JobPipeline;
use Stancl\Tenancy\Events\Listeners\RevertToCentralContext;
use Stancl\Tenancy\Events\TenancyEnded;
use Stancl\Tenancy\Events\TenancyInitialized;
use Stancl\Tenancy\Events\TenantCreated;
use Stancl\Tenancy\Jobs\CreateDatabase;
use Stancl\Tenancy\TenancyBootstrappers\CacheTenancyBootstrapper;
use Stancl\Tenancy\TenancyBootstrappers\DatabaseTenancyBootstrapper;
use Stancl\Tenancy\TenancyBootstrappers\FilesystemTenancyBootstrapper;
use Stancl\Tenancy\TenancyBootstrappers\RedisTenancyBootstrapper;
use Stancl\Tenancy\Tests\TestCase;
class BootstrapperTest extends TestCase
{
public $mockConsoleOutput = false;
public function setUp(): void
{
parent::setUp();
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);
}
/** @test */
public function database_data_is_separated()
{
config(['tenancy.bootstrappers' => [
DatabaseTenancyBootstrapper::class
]]);
$tenant1 = Tenant::create();
$tenant2 = Tenant::create();
$this->artisan('tenants:migrate');
tenancy()->initialize($tenant1);
// Create Foo user
DB::table('users')->insert(['name' => 'Foo', 'email' => 'foo@bar.com', 'password' => 'secret']);
$this->assertCount(1, DB::table('users')->get());
tenancy()->initialize($tenant2);
// Assert Foo user is not in this DB
$this->assertCount(0, DB::table('users')->get());
// Create Bar user
DB::table('users')->insert(['name' => 'Bar', 'email' => 'bar@bar.com', 'password' => 'secret']);
$this->assertCount(1, DB::table('users')->get());
tenancy()->initialize($tenant1);
// Assert Bar user is not in this DB
$this->assertCount(1, DB::table('users')->get());
$this->assertSame('Foo', DB::table('users')->first()->name);
}
/** @test */
public function cache_data_is_separated()
{
config([
'tenancy.bootstrappers' => [
CacheTenancyBootstrapper::class
],
'cache.default' => 'redis',
]);
$tenant1 = Tenant::create();
$tenant2 = Tenant::create();
cache()->set('foo', 'central');
$this->assertSame('central', Cache::get('foo'));
tenancy()->initialize($tenant1);
// Assert central cache doesn't leak to tenant context
$this->assertFalse(Cache::has('foo'));
cache()->set('foo', 'bar');
$this->assertSame('bar', Cache::get('foo'));
tenancy()->initialize($tenant2);
// Assert one tenant's data doesn't leak to another tenant
$this->assertFalse(Cache::has('foo'));
cache()->set('foo', 'xyz');
$this->assertSame('xyz', Cache::get('foo'));
tenancy()->initialize($tenant1);
// Asset data didn't leak to original tenant
$this->assertSame('bar', Cache::get('foo'));
tenancy()->end();
// Asset central is still the same
$this->assertSame('central', Cache::get('foo'));
}
/** @test */
public function redis_data_is_separated()
{
config(['tenancy.bootstrappers' => [
RedisTenancyBootstrapper::class
]]);
$tenant1 = Tenant::create();
$tenant2 = Tenant::create();
tenancy()->initialize($tenant1);
Redis::set('foo', 'bar');
$this->assertSame('bar', Redis::get('foo'));
tenancy()->initialize($tenant2);
$this->assertSame(null, Redis::get('foo'));
Redis::set('foo', 'xyz');
Redis::set('abc', 'def');
$this->assertSame('xyz', Redis::get('foo'));
$this->assertSame('def', Redis::get('abc'));
tenancy()->initialize($tenant1);
$this->assertSame('bar', Redis::get('foo'));
$this->assertSame(null, Redis::get('abc'));
$tenant3 = Tenant::create();
tenancy()->initialize($tenant3);
$this->assertSame(null, Redis::get('foo'));
$this->assertSame(null, Redis::get('abc'));
}
/** @test */
public function filesystem_data_is_separated()
{
config(['tenancy.bootstrappers' => [
FilesystemTenancyBootstrapper::class
]]);
$tenant1 = Tenant::create();
$tenant2 = Tenant::create();
tenancy()->initialize($tenant1);
Storage::disk('public')->put('foo', 'bar');
$this->assertSame('bar', Storage::disk('public')->get('foo'));
tenancy()->initialize($tenant2);
$this->assertFalse(Storage::disk('public')->exists('foo'));
Storage::disk('public')->put('foo', 'xyz');
Storage::disk('public')->put('abc', 'def');
$this->assertSame('xyz', Storage::disk('public')->get('foo'));
$this->assertSame('def', Storage::disk('public')->get('abc'));
tenancy()->initialize($tenant1);
$this->assertSame('bar', Storage::disk('public')->get('foo'));
$this->assertFalse(Storage::disk('public')->exists('abc'));
$tenant3 = Tenant::create();
tenancy()->initialize($tenant3);
$this->assertFalse(Storage::disk('public')->exists('foo'));
$this->assertFalse(Storage::disk('public')->exists('abc'));
}
// for queues see QueueTest
}

View file

@ -1,78 +0,0 @@
<?php
namespace Stancl\Tenancy\Tests\v3;
use Illuminate\Support\Facades\Route;
use Stancl\Tenancy\Database\Models;
use Stancl\Tenancy\Database\Models\Concerns\HasDomains;
use Stancl\Tenancy\Middleware\InitializeTenancyByDomainOrSubdomain;
use Stancl\Tenancy\Tests\TestCase;
class CombinedDomainAndSubdomainIdentificationTest extends TestCase
{
public function setUp(): void
{
parent::setUp();
Route::group([
'middleware' => InitializeTenancyByDomainOrSubdomain::class,
], function () {
Route::get('/foo/{a}/{b}', function ($a, $b) {
return "$a + $b";
});
});
config(['tenancy.tenant_model' => Tenant::class]);
}
/** @test */
public function tenant_can_be_identified_by_subdomain()
{
config(['tenancy.central_domains' => ['localhost']]);
$tenant = Tenant::create([
'id' => 'acme',
]);
$tenant->domains()->create([
'domain' => 'foo',
]);
$this->assertFalse(tenancy()->initialized);
$this
->get('http://foo.localhost/foo/abc/xyz')
->assertSee('abc + xyz');
$this->assertTrue(tenancy()->initialized);
$this->assertSame('acme', tenant('id'));
}
/** @test */
public function tenant_can_be_identified_by_domain()
{
config(['tenancy.central_domains' => []]);
$tenant = Tenant::create([
'id' => 'acme',
]);
$tenant->domains()->create([
'domain' => 'foobar.localhost',
]);
$this->assertFalse(tenancy()->initialized);
$this
->get('http://foobar.localhost/foo/abc/xyz')
->assertSee('abc + xyz');
$this->assertTrue(tenancy()->initialized);
$this->assertSame('acme', tenant('id'));
}
}
class Tenant extends Models\Tenant
{
use HasDomains;
}

View file

@ -1 +0,0 @@
// test DB creation, migration, seeding

View file

@ -1,110 +0,0 @@
<?php
namespace Stancl\Tenancy\Tests\v3;
use Illuminate\Support\Facades\Route;
use Stancl\Tenancy\Database\Models;
use Stancl\Tenancy\Database\Models\Concerns\HasDomains;
use Stancl\Tenancy\Exceptions\DomainOccupiedByOtherTenantException;
use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedOnDomainException;
use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
use Stancl\Tenancy\Resolvers\DomainTenantResolver;
use Stancl\Tenancy\Tests\TestCase;
class DomainTest extends TestCase
{
public function setUp(): void
{
parent::setUp();
Route::group([
'middleware' => InitializeTenancyByDomain::class,
], function () {
Route::get('/foo/{a}/{b}', function ($a, $b) {
return "$a + $b";
});
});
config(['tenancy.tenant_model' => Tenant::class]);
}
/** @test */
public function tenant_can_be_identified_using_hostname()
{
$tenant = Tenant::create();
$id = $tenant->id;
$tenant->domains()->create([
'domain' => 'foo.localhost',
]);
$resolvedTenant = app(DomainTenantResolver::class)->resolve('foo.localhost');
$this->assertSame($id, $resolvedTenant->id);
$this->assertSame(['foo.localhost'], $resolvedTenant->domains->pluck('domain')->toArray());
}
/** @test */
public function a_domain_can_belong_to_only_one_tenant()
{
$tenant = Tenant::create();
$tenant->domains()->create([
'domain' => 'foo.localhost',
]);
$tenant2 = Tenant::create();
$this->expectException(DomainOccupiedByOtherTenantException::class);
$tenant2->domains()->create([
'domain' => 'foo.localhost',
]);
}
/** @test */
public function an_exception_is_thrown_if_tenant_cannot_be_identified()
{
$this->expectException(TenantCouldNotBeIdentifiedOnDomainException::class);
app(DomainTenantResolver::class)->resolve('foo.localhost');
}
/** @test */
public function tenant_can_be_identified_by_domain()
{
$tenant = Tenant::create([
'id' => 'acme',
]);
$tenant->domains()->create([
'domain' => 'foo.localhost',
]);
$this->assertFalse(tenancy()->initialized);
$this
->get('http://foo.localhost/foo/abc/xyz')
->assertSee('abc + xyz');
$this->assertTrue(tenancy()->initialized);
$this->assertSame('acme', tenant('id'));
}
/** @test */
public function onfail_logic_can_be_customized()
{
InitializeTenancyByDomain::$onFail = function () {
return 'foo';
};
$this
->get('http://foo.localhost/foo/abc/xyz')
->assertSee('foo');
}
}
class Tenant extends Models\Tenant
{
use HasDomains;
}

View file

@ -1,56 +0,0 @@
<?php
namespace Stancl\Tenancy\Tests\v3;
use Illuminate\Events\CallQueuedListener;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Queue;
use Stancl\Tenancy\Database\Models\Tenant;
use Stancl\Tenancy\Events\Listeners\QueueableListener;
use Stancl\Tenancy\Events\TenantCreated;
use Stancl\Tenancy\Tests\TestCase;
class EventListenerTest extends TestCase
{
/** @test */
public function listeners_can_be_synchronous()
{
Queue::fake();
Event::listen(TenantCreated::class, FooListener::class);
Tenant::create();
Queue::assertNothingPushed();
$this->assertSame('bar', app('foo'));
}
/** @test */
public function listeners_can_be_queued_by_setting_a_static_property()
{
Queue::fake();
Event::listen(TenantCreated::class, FooListener::class);
FooListener::$shouldQueue = true;
Tenant::create();
Queue::assertPushed(CallQueuedListener::class, function (CallQueuedListener $job) {
return $job->class === FooListener::class;
});
$this->assertFalse(app()->bound('foo'));
}
// todo test that the way the published SP registers events works
}
class FooListener extends QueueableListener
{
public static $shouldQueue = false;
public function handle()
{
app()->instance('foo', 'bar');
}
}

View file

@ -1,180 +0,0 @@
<?php
namespace Stancl\Tenancy\Tests\v3;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Queue;
use Spatie\Valuestore\Valuestore;
use Stancl\Tenancy\Database\Models\Tenant;
use Stancl\Tenancy\Events\Listeners\JobPipeline;
use Stancl\Tenancy\Events\TenantCreated;
use Stancl\Tenancy\Tests\TestCase;
class JobPipelineTest extends TestCase
{
public $mockConsoleOutput = false;
/** @var Valuestore */
protected $valuestore;
public function setUp(): void
{
parent::setUp();
config(['queue.default' => 'redis']);
$this->valuestore = Valuestore::make(__DIR__ . '/../Etc/tmp/jobpipelinetest.json')->flush();
}
/** @test */
public function job_pipeline_can_listen_to_any_event()
{
Event::listen(TenantCreated::class, JobPipeline::make([
FooJob::class,
])->send(function () {
return $this->valuestore;
})->toListener());
$this->assertFalse($this->valuestore->has('foo'));
Tenant::create();
$this->assertSame('bar', $this->valuestore->get('foo'));
}
/** @test */
public function job_pipeline_can_be_queued()
{
Queue::fake();
Event::listen(TenantCreated::class, JobPipeline::make([
FooJob::class,
])->send(function () {
return $this->valuestore;
})->shouldBeQueued(true)->toListener());
Queue::assertNothingPushed();
Tenant::create();
$this->assertFalse($this->valuestore->has('foo'));
Queue::pushed(JobPipeline::class, function (JobPipeline $pipeline) {
$this->assertSame([FooJob::class], $pipeline->jobs);
});
}
/** @test */
public function job_pipelines_run_when_queued()
{
Event::listen(TenantCreated::class, JobPipeline::make([
FooJob::class,
])->send(function () {
return $this->valuestore;
})->shouldBeQueued(true)->toListener());
$this->assertFalse($this->valuestore->has('foo'));
Tenant::create();
$this->artisan('queue:work --once');
$this->assertSame('bar', $this->valuestore->get('foo'));
}
/** @test */
public function job_pipeline_executes_jobs_and_passes_the_object_sequentially()
{
Event::listen(TenantCreated::class, JobPipeline::make([
FirstJob::class,
SecondJob::class,
])->send(function (TenantCreated $event) {
return [$event->tenant, $this->valuestore];
})->toListener());
$this->assertFalse($this->valuestore->has('foo'));
Tenant::create();
$this->assertSame('first job changed property', $this->valuestore->get('foo'));
}
/** @test */
public function send_can_return_multiple_arguments()
{
Event::listen(TenantCreated::class, JobPipeline::make([
JobWithMultipleArguments::class
])->send(function () {
return ['a', 'b'];
})->toListener());
$this->assertFalse(app()->bound('test_args'));
Tenant::create();
$this->assertSame(['a', 'b'], app('test_args'));
}
}
class FooJob
{
protected $valuestore;
public function __construct(Valuestore $valuestore)
{
$this->valuestore = $valuestore;
}
public function handle()
{
$this->valuestore->put('foo', 'bar');
}
};
class FirstJob
{
public $tenant;
public function __construct(Tenant $tenant)
{
$this->tenant = $tenant;
}
public function handle()
{
$this->tenant->foo = 'first job changed property';
}
}
class SecondJob
{
public $tenant;
protected $valuestore;
public function __construct(Tenant $tenant, Valuestore $valuestore)
{
$this->tenant = $tenant;
$this->valuestore = $valuestore;
}
public function handle()
{
$this->valuestore->put('foo', $this->tenant->foo);
}
}
class JobWithMultipleArguments
{
protected $first;
protected $second;
public function __construct($first, $second)
{
$this->first = $first;
$this->second = $second;
}
public function handle()
{
// we dont queue this job so no need to use valuestore here
app()->instance('test_args', [$this->first, $this->second]);
}
}

View file

@ -1,140 +0,0 @@
<?php
namespace Stancl\Tenancy\Tests\v3;
use Illuminate\Support\Facades\Route;
use Stancl\Tenancy\Database\Models\Tenant;
use Stancl\Tenancy\Exceptions\RouteIsMissingTenantParameterException;
use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedByPathException;
use Stancl\Tenancy\Middleware\InitializeTenancyByPath;
use Stancl\Tenancy\Resolvers\PathTenantResolver;
use Stancl\Tenancy\Tests\TestCase;
class PathIdentificationTest extends TestCase
{
public function setUp(): void
{
parent::setUp();
PathTenantResolver::$tenantParameterName = 'tenant';
Route::group([
'prefix' => '/{tenant}',
'middleware' => InitializeTenancyByPath::class,
], function () {
Route::get('/foo/{a}/{b}', function ($a, $b) {
return "$a + $b";
});
});
}
/** @test */
public function tenant_can_be_identified_by_path()
{
Tenant::create([
'id' => 'acme',
]);
$this->assertFalse(tenancy()->initialized);
$this->get('/acme/foo/abc/xyz');
$this->assertTrue(tenancy()->initialized);
$this->assertSame('acme', tenant('id'));
}
/** @test */
public function route_actions_dont_get_the_tenant_id()
{
Tenant::create([
'id' => 'acme',
]);
$this->assertFalse(tenancy()->initialized);
$this
->get('/acme/foo/abc/xyz')
->assertContent('abc + xyz');
$this->assertTrue(tenancy()->initialized);
$this->assertSame('acme', tenant('id'));
}
/** @test */
public function exception_is_thrown_when_tenant_cannot_be_identified_by_path()
{
$this->expectException(TenantCouldNotBeIdentifiedByPathException::class);
$this
->withoutExceptionHandling()
->get('/acme/foo/abc/xyz');
$this->assertFalse(tenancy()->initialized);
}
/** @test */
public function onfail_logic_can_be_customized()
{
InitializeTenancyByPath::$onFail = function () {
return 'foo';
};
$this
->get('/acme/foo/abc/xyz')
->assertContent('foo');
}
/** @test */
public function an_exception_is_thrown_when_the_routes_first_parameter_is_not_tenant()
{
Route::group([
// 'prefix' => '/{tenant}', -- intentionally commented
'middleware' => InitializeTenancyByPath::class,
], function () {
Route::get('/bar/{a}/{b}', function ($a, $b) {
return "$a + $b";
});
});
Tenant::create([
'id' => 'acme',
]);
$this->expectException(RouteIsMissingTenantParameterException::class);
$this
->withoutExceptionHandling()
->get('/bar/foo/bar');
}
/** @test */
public function tenant_parameter_name_can_be_customized()
{
PathTenantResolver::$tenantParameterName = 'team';
Route::group([
'prefix' => '/{team}',
'middleware' => InitializeTenancyByPath::class,
], function () {
Route::get('/bar/{a}/{b}', function ($a, $b) {
return "$a + $b";
});
});
Tenant::create([
'id' => 'acme',
]);
$this
->get('/acme/bar/abc/xyz')
->assertContent('abc + xyz');
// Parameter for resolver is changed, so the /{tenant}/foo route will no longer work.
$this->expectException(RouteIsMissingTenantParameterException::class);
$this
->withoutExceptionHandling()
->get('/acme/foo/abc/xyz');
}
}

View file

@ -1,136 +0,0 @@
<?php
namespace Stancl\Tenancy\Tests\v3;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
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\Database\Models\Tenant;
use Stancl\Tenancy\Events\Listeners\BootstrapTenancy;
use Stancl\Tenancy\Events\TenancyInitialized;
use Stancl\Tenancy\TenancyBootstrappers\QueueTenancyBootstrapper;
use Stancl\Tenancy\Tests\TestCase;
class QueueTest extends TestCase
{
public $mockConsoleOutput = false;
/** @var Valuestore */
protected $valuestore;
public function setUp(): void
{
parent::setUp();
config([
'tenancy.bootstrappers' => [
QueueTenancyBootstrapper::class,
],
'queue.default' => 'redis',
]);
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
$this->valuestore = Valuestore::make(__DIR__ . '/../Etc/tmp/queuetest.json')->flush();
}
/** @test */
public function tenant_id_is_passed_to_tenant_queues()
{
$tenant = Tenant::create();
tenancy()->initialize($tenant);
Event::fake();
dispatch(new TestJob($this->valuestore));
Event::assertDispatched(JobProcessing::class, function ($event) {
return $event->job->payload()['tenant_id'] === tenant('id');
});
}
/** @test */
public function tenant_id_is_not_passed_to_central_queues()
{
$tenant = Tenant::create();
tenancy()->initialize($tenant);
Event::fake();
config(['queue.connections.central' => [
'driver' => 'sync',
'central' => true,
]]);
dispatch(new TestJob($this->valuestore))->onConnection('central');
Event::assertDispatched(JobProcessing::class, function ($event) {
return ! isset($event->job->payload()['tenant_id']);
});
}
/** @test */
public function tenancy_is_initialized_inside_queues()
{
$tenant = Tenant::create([
'id' => 'acme',
]);
tenancy()->initialize($tenant);
dispatch(new TestJob($this->valuestore));
$this->assertFalse($this->valuestore->has('tenant_id'));
$this->artisan('queue:work --once');
$this->assertSame('The current tenant id is: acme', $this->valuestore->get('tenant_id'));
}
/** @test */
public function the_tenant_used_by_the_job_doesnt_change_when_the_current_tenant_changes()
{
$tenant1 = Tenant::create([
'id' => 'acme',
]);
tenancy()->initialize($tenant1);
dispatch(new TestJob($this->valuestore));
$tenant2 = Tenant::create([
'id' => 'foobar',
]);
tenancy()->initialize($tenant2);
$this->assertFalse($this->valuestore->has('tenant_id'));
$this->artisan('queue:work --once');
$this->assertSame('The current tenant id is: acme', $this->valuestore->get('tenant_id'));
}
}
class TestJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/** @var Valuestore */
protected $valuestore;
public function __construct(Valuestore $valuestore)
{
$this->valuestore = $valuestore;
}
public function handle()
{
$this->valuestore->put('tenant_id', "The current tenant id is: " . tenant('id'));
}
}

View file

@ -1,127 +0,0 @@
<?php
namespace Stancl\Tenancy\Tests\v3;
use Illuminate\Support\Facades\Route;
use Stancl\Tenancy\Database\Models;
use Stancl\Tenancy\Database\Models\Concerns\HasDomains;
use Stancl\Tenancy\Exceptions\NotASubdomainException;
use Stancl\Tenancy\Middleware\InitializeTenancyBySubdomain;
use Stancl\Tenancy\Tests\TestCase;
class SubdomainTest extends TestCase
{
public function setUp(): void
{
parent::setUp();
// Global state cleanup after some tests
InitializeTenancyBySubdomain::$onInvalidSubdomain = null;
Route::group([
'middleware' => InitializeTenancyBySubdomain::class,
], function () {
Route::get('/foo/{a}/{b}', function ($a, $b) {
return "$a + $b";
});
});
config(['tenancy.tenant_model' => Tenant::class]);
}
/** @test */
public function tenant_can_be_identified_by_subdomain()
{
$tenant = Tenant::create([
'id' => 'acme',
]);
$tenant->domains()->create([
'domain' => 'foo',
]);
$this->assertFalse(tenancy()->initialized);
$this
->get('http://foo.localhost/foo/abc/xyz')
->assertSee('abc + xyz');
$this->assertTrue(tenancy()->initialized);
$this->assertSame('acme', tenant('id'));
}
/** @test */
public function onfail_logic_can_be_customized()
{
InitializeTenancyBySubdomain::$onFail = function () {
return 'foo';
};
$this
->get('http://foo.localhost/foo/abc/xyz')
->assertSee('foo');
}
/** @test */
public function localhost_is_not_a_valid_subdomain()
{
$this->expectException(NotASubdomainException::class);
$this
->withoutExceptionHandling()
->get('http://localhost/foo/abc/xyz');
}
/** @test */
public function ip_address_is_not_a_valid_subdomain()
{
$this->expectException(NotASubdomainException::class);
$this
->withoutExceptionHandling()
->get('http://127.0.0.1/foo/abc/xyz');
}
/** @test */
public function oninvalidsubdomain_logic_can_be_customized()
{
// in this case, we need to return a response instance
// since a string would be treated as the subdomain
InitializeTenancyBySubdomain::$onInvalidSubdomain = function () {
return response('foo custom invalid subdomain handler');
};
$this
->withoutExceptionHandling()
->get('http://127.0.0.1/foo/abc/xyz')
->assertSee('foo custom invalid subdomain handler');
}
/** @test */
public function we_cant_use_a_subdomain_that_doesnt_belong_to_our_central_domains()
{
config(['tenancy.central_domains' => [
'127.0.0.1',
// not 'localhost'
]]);
$tenant = Tenant::create([
'id' => 'acme',
]);
$tenant->domains()->create([
'domain' => 'foo',
]);
$this->expectException(NotASubdomainException::class);
$this
->withoutExceptionHandling()
->get('http://foo.localhost/foo/abc/xyz');
}
}
class Tenant extends Models\Tenant
{
use HasDomains;
}

View file

@ -1,156 +0,0 @@
<?php
namespace Stancl\Tenancy\Tests\v3;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Schema;
use Stancl\Tenancy\Database\Models\Tenant;
use Stancl\Tenancy\Events\TenantCreated;
use Stancl\Tenancy\Tests\TestCase;
use Stancl\Tenancy\UniqueIDGenerators\UUIDGenerator;
use Stancl\Tenancy\Contracts;
class TenantModelTest extends TestCase
{
/** @test */
public function created_event_is_dispatched()
{
Event::fake([TenantCreated::class]);
Event::assertNotDispatched(TenantCreated::class);
Tenant::create();
Event::assertDispatched(TenantCreated::class);
}
/** @test */
public function current_tenant_can_be_resolved_from_service_container_using_typehint()
{
$tenant = Tenant::create();
tenancy()->initialize($tenant);
$this->assertSame($tenant->id, app(Tenant::class)->id);
tenancy()->end();
$this->assertSame(null, app(Tenant::class));
}
/** @test */
public function keys_which_dont_have_their_own_column_go_into_data_json_column()
{
$tenant = Tenant::create([
'foo' => 'bar',
]);
// Test that model works correctly
$this->assertSame('bar', $tenant->foo);
$this->assertSame(null, $tenant->data);
// Low level test to test database structure
$this->assertSame(json_encode(['foo' => 'bar']), DB::table('tenants')->where('id', $tenant->id)->first()->data);
$this->assertSame(null, DB::table('tenants')->where('id', $tenant->id)->first()->foo ?? null);
// Model has the correct structure when retrieved
$tenant = Tenant::first();
$this->assertSame('bar', $tenant->foo);
$this->assertSame(null, $tenant->data);
// Model can be updated
$tenant->update([
'foo' => 'baz',
'abc' => 'xyz',
]);
$this->assertSame('baz', $tenant->foo);
$this->assertSame('xyz', $tenant->abc);
$this->assertSame(null, $tenant->data);
// Model can be retrieved after update & is structure correctly
$tenant = Tenant::first();
$this->assertSame('baz', $tenant->foo);
$this->assertSame('xyz', $tenant->abc);
$this->assertSame(null, $tenant->data);
}
/** @test */
public function id_is_generated_when_no_id_is_supplied()
{
config(['tenancy.id_generator' => UUIDGenerator::class]);
$this->mock(UUIDGenerator::class, function ($mock) {
return $mock->shouldReceive('generate')->once();
});
$tenant = Tenant::create();
$this->assertNotNull($tenant->id);
}
/** @test */
public function autoincrement_ids_are_supported()
{
Schema::table('tenants', function (Blueprint $table) {
$table->bigIncrements('id')->change();
});
config(['tenancy.id_generator' => null]);
$tenant1 = Tenant::create();
$tenant2 = Tenant::create();
$this->assertSame(1, $tenant1->id);
$this->assertSame(2, $tenant2->id);
}
/** @test */
public function custom_tenant_model_can_be_used()
{
$tenant = MyTenant::create();
tenancy()->initialize($tenant);
$this->assertTrue(tenant() instanceof MyTenant);
}
/** @test */
public function custom_tenant_model_that_doesnt_extend_vendor_Tenant_model_can_be_used()
{
$tenant = AnotherTenant::create([
'id' => 'acme',
]);
tenancy()->initialize($tenant);
$this->assertTrue(tenant() instanceof AnotherTenant);
}
// todo test that tenant can be created even in another DB context - that the central trait works
}
class MyTenant extends Tenant
{
protected $table = 'tenants';
}
class AnotherTenant extends Model implements Contracts\Tenant
{
protected $guarded = [];
protected $table = 'tenants';
public function getTenantKeyName(): string
{
return 'id';
}
public function getTenantKey(): string
{
return $this->getAttribute('id');
}
}