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

Shared users - complete

This commit is contained in:
Samuel Štancl 2020-05-12 01:54:02 +02:00
parent daae67c0f7
commit b7c8f1fba7
12 changed files with 488 additions and 56 deletions

View file

@ -3,12 +3,13 @@
namespace Stancl\Tenancy\Contracts;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
// todo rename?
/**
* @property-read Tenant[]|Collection $tenants
*/
interface SyncMaster extends Syncable
{
public function tenants(); // Probably should return BelongsToMany
}
public function tenants(): BelongsToMany;
public function getTenantModelName(): string;
}

View file

@ -2,11 +2,10 @@
namespace Stancl\Tenancy\Contracts;
// todo add comments
interface Syncable
{
public function getGlobalIdentifierKeyName(): string;
public function getGlobalIdentifierKey(): string;
public function getCentralModelName(): string;
public function getSyncedAttributeNames(): array;
}
}

View file

@ -4,12 +4,12 @@ declare(strict_types=1);
namespace Stancl\Tenancy\Contracts;
use Stancl\Tenancy\Database\Models\Tenant;
use Illuminate\Database\Eloquent\Model;
interface UniqueIdentifierGenerator
{
/**
* Generate a unique identifier.
*/
public static function generate(Tenant $tenant): string;
public static function generate(Model $model): string;
}

View file

@ -3,14 +3,32 @@
namespace Stancl\Tenancy\Database\Models\Concerns;
use Stancl\Tenancy\Contracts\Syncable;
use Stancl\Tenancy\Contracts\UniqueIdentifierGenerator;
use Stancl\Tenancy\Events\SyncedResourceSaved;
trait ResourceSyncing
{
public static function bootResourceSyncing()
{
static::saving(function (Syncable $model) {
event(new SyncedResourceSaved($model, tenant()));
static::saved(function (Syncable $model) {
/** @var ResourceSyncing $model */
$model->triggerSyncEvent();
});
static::creating(function (self $model) {
if (! $model->getAttribute($model->getGlobalIdentifierKeyName()) && app()->bound(UniqueIdentifierGenerator::class)) {
$model->setAttribute(
$model->getGlobalIdentifierKeyName(),
app(UniqueIdentifierGenerator::class)->generate($model)
);
}
});
}
public function triggerSyncEvent()
{
/** @var Syncable $this */
event(new SyncedResourceSaved($this, tenant()));
}
}

View file

@ -0,0 +1,15 @@
<?php
namespace Stancl\Tenancy\Database\Models;
use Illuminate\Database\Eloquent\Relations\Pivot;
class TenantPivot extends Pivot
{
public static function booted()
{
static::saved(function (self $pivot) {
$pivot->pivotParent->triggerSyncEvent();
});
}
}

View file

@ -42,9 +42,9 @@ class DatabaseManager
*/
public function connectToTenant(TenantWithDatabase $tenant)
{
$this->database->purge('tenant');
$this->createTenantConnection($tenant);
$this->setDefaultConnection('tenant');
$this->database->purge('tenant');
}
/**
@ -55,6 +55,7 @@ class DatabaseManager
if (tenancy()->initialized) {
$this->database->purge('tenant');
}
$this->setDefaultConnection($this->config->get('tenancy.central_connection'));
}

View file

@ -4,12 +4,13 @@ namespace Stancl\Tenancy\Events\Listeners;
use Illuminate\Contracts\Queue\ShouldQueue;
/**
* @method handle(object $event)
*/
abstract class QueueableListener implements ShouldQueue
{
public static $shouldQueue = false;
abstract public function handle();
public function shouldQueue($event)
{
if (static::$shouldQueue) {

View file

@ -3,12 +3,15 @@
namespace Stancl\Tenancy\Events\Listeners;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Pivot;
use Stancl\Tenancy\Contracts\SyncMaster;
use Stancl\Tenancy\Contracts\Tenant;
use Stancl\Tenancy\Events\SyncedResourceSaved;
use Stancl\Tenancy\Exceptions\ModelNotSyncMaster;
class UpdateSyncedResource
class UpdateSyncedResource extends QueueableListener
{
public static $shouldQueue = false;
public function handle(SyncedResourceSaved $event)
{
$syncedAttributes = $event->model->only($event->model->getSyncedAttributeNames());
@ -19,36 +22,76 @@ class UpdateSyncedResource
$centralModel = $event->model->getCentralModelName()
::where($event->model->getGlobalIdentifierKeyName(), $event->model->getGlobalIdentifierKey())
->first();
// We disable events for this call, to avoid triggering this event & listener again.
$centralModel->withoutEvents(function () use ($centralModel, $syncedAttributes) {
$centralModel->update($syncedAttributes);
$event->model->getCentralModelName()::withoutEvents(function () use (&$centralModel, $syncedAttributes, $event) {
if ($centralModel) {
$centralModel->update($syncedAttributes);
} else {
// If the resource doesn't exist at all in the central DB,we create
// the record with all attributes, not just the synced ones.
$centralModel = $event->model->getCentralModelName()::create($event->model->getAttributes());
}
});
// If the model was just created, the mapping of the tenant to the user likely doesn't exist, so we create it.
$mappingExists = $centralModel->tenants->contains(function ($model) use ($event) {
return $model->tenant_id === $event->tenant->getTenantKey();
});
if (! $mappingExists) {
// Here we should call TenantPivot, but we call general Pivot, so that this works
// even if people use their own pivot model that is not based on our TenantPivot
Pivot::withoutEvents(function () use ($centralModel, $event) {
$centralModel->tenants()->attach($event->tenant->getTenantKey());
});
}
$tenants = $centralModel->tenants->except($event->tenant->getTenantKey());
} else {
$centralModel = $event->model;
if (! $centralModel instanceof SyncMaster) {
// If we're trying to use a tenant User model instead of the central User model, for example.
throw new ModelNotSyncMaster(get_class($centralModel));
}
/** @var SyncMaster|Model $centralModel */
// Since this model is "dirty" (taken by reference from the event), it might have the tenants
// relationship already loaded and cached. For this reason, we refresh the relationship.
$centralModel->load('tenants');
$tenants = $centralModel->tenants;
}
foreach ($tenants as $tenant) {
// todo: performance optimization - $tenant->run() does tenancy()->end() after each call.
// we dont want that when we want to initialize for the next tenant afterwards rather than for the previous tenant
// so we should write a method like run() for running things on multiple tenants efficiently
tenancy()->runForMultiple($tenants, function () use ($event, $syncedAttributes) {
// Forget instance state and find the model,
// again in the current tenant's context.
$tenant->run(function () use ($event, $syncedAttributes) {
// Forget instance state and find the model,
// again in the current tenant's context.
$eventModel = $event->model;
/** @var Tenant|Model $model */
$localModel = $event->model::find($event->model->getKey());
if ($eventModel instanceof SyncMaster) {
// If event model comes from central DB, we get the tenant model name to run the query
$localModelClass = $eventModel->getTenantModelName();
} else {
$localModelClass = get_class($eventModel);
}
// Also: We're syncing attributes, not columns, which is
// why we're using Eloquent instead of direct DB queries.
/** @var Model|null */
$localModel = $localModelClass::firstWhere($event->model->getGlobalIdentifierKeyName(), $event->model->getGlobalIdentifierKey());
// We disable events for this call, to avoid triggering this event & listener again.
$localModel->update($syncedAttributes);
// Also: We're syncing attributes, not columns, which is
// why we're using Eloquent instead of direct DB queries.
// We disable events for this call, to avoid triggering this event & listener again.
$localModelClass::withoutEvents(function () use ($localModelClass, $localModel, $syncedAttributes, $eventModel) {
if ($localModel) {
$localModel->update($syncedAttributes);
} else {
// When creating, we use all columns, not just the synced ones.
$localModelClass::create($eventModel->getAttributes());
}
});
}
});
}
}

View file

@ -0,0 +1,13 @@
<?php
namespace Stancl\Tenancy\Exceptions;
use Exception;
class ModelNotSyncMaster extends Exception
{
public function __construct(string $class)
{
parent::__construct("Model of $class class is not an SyncMaster model. Make sure you're using the central model to make changes to synced resouces when you're in the central context");
}
}

View file

@ -33,6 +33,10 @@ class Tenancy
public function end(): void
{
if (! $this->initialized) {
return;
}
$this->initialized = false;
event(new Events\TenancyEnded($this));
@ -68,4 +72,28 @@ class Tenancy
{
return $this->model()->find($id);
}
/**
* Run a callback for multiple tenants.
* More performant than running $tenant->run() one by one.
*
* @param Tenant[]|\Illuminate\Support\Collection $tenants
* @param callable $callback
* @return void
*/
public function runForMultiple($tenants, callable $callback)
{
$originalTenant = $this->tenant;
foreach ($tenants as $tenant) {
$this->initialize($tenant);
$callback($tenant);
}
if ($originalTenant) {
$this->initialize($originalTenant);
} else {
$this->end();
}
}
}

View file

@ -4,13 +4,13 @@ declare(strict_types=1);
namespace Stancl\Tenancy\UniqueIDGenerators;
use Illuminate\Database\Eloquent\Model;
use Ramsey\Uuid\Uuid;
use Stancl\Tenancy\Contracts\UniqueIdentifierGenerator;
use Stancl\Tenancy\Database\Models\Tenant;
class UUIDGenerator implements UniqueIdentifierGenerator
{
public static function generate(Tenant $tenant): string
public static function generate(Model $model): string
{
return Uuid::uuid4()->toString();
}