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

Merge branch 'master' into cache-prefix

This commit is contained in:
lukinovec 2023-02-21 10:22:17 +01:00 committed by GitHub
commit 249fc545d2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
22 changed files with 564 additions and 38 deletions

View file

@ -0,0 +1,95 @@
<?php
declare(strict_types=1);
namespace Stancl\Tenancy\Bootstrappers;
use Illuminate\Broadcasting\BroadcastManager;
use Illuminate\Config\Repository;
use Illuminate\Contracts\Broadcasting\Broadcaster;
use Illuminate\Foundation\Application;
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
use Stancl\Tenancy\Contracts\Tenant;
use Stancl\Tenancy\TenancyBroadcastManager;
class BroadcastTenancyBootstrapper implements TenancyBootstrapper
{
/**
* Tenant properties to be mapped to config (similarly to the TenantConfig feature).
*
* For example:
* [
* 'config.key.name' => 'tenant_property',
* ]
*/
public static array $credentialsMap = [];
public static string|null $broadcaster = null;
protected array $originalConfig = [];
protected BroadcastManager|null $originalBroadcastManager = null;
protected Broadcaster|null $originalBroadcaster = null;
public static array $mapPresets = [
'pusher' => [
'broadcasting.connections.pusher.key' => 'pusher_key',
'broadcasting.connections.pusher.secret' => 'pusher_secret',
'broadcasting.connections.pusher.app_id' => 'pusher_app_id',
'broadcasting.connections.pusher.options.cluster' => 'pusher_cluster',
],
'ably' => [
'broadcasting.connections.ably.key' => 'ably_key',
'broadcasting.connections.ably.public' => 'ably_public',
],
];
public function __construct(
protected Repository $config,
protected Application $app
) {
static::$broadcaster ??= $config->get('broadcasting.default');
static::$credentialsMap = array_merge(static::$credentialsMap, static::$mapPresets[static::$broadcaster] ?? []);
}
public function bootstrap(Tenant $tenant): void
{
$this->originalBroadcastManager = $this->app->make(BroadcastManager::class);
$this->originalBroadcaster = $this->app->make(Broadcaster::class);
$this->setConfig($tenant);
// Make BroadcastManager resolve to a custom BroadcastManager which makes the broadcasters use the tenant credentials
$this->app->extend(BroadcastManager::class, function (BroadcastManager $broadcastManager) {
return new TenancyBroadcastManager($this->app);
});
}
public function revert(): void
{
// Change the BroadcastManager and Broadcaster singletons back to what they were before initializing tenancy
$this->app->singleton(BroadcastManager::class, fn (Application $app) => $this->originalBroadcastManager);
$this->app->singleton(Broadcaster::class, fn (Application $app) => $this->originalBroadcaster);
$this->unsetConfig();
}
protected function setConfig(Tenant $tenant): void
{
foreach (static::$credentialsMap as $configKey => $storageKey) {
$override = $tenant->$storageKey;
if (array_key_exists($storageKey, $tenant->getAttributes())) {
$this->originalConfig[$configKey] ??= $this->config->get($configKey);
$this->config->set($configKey, $override);
}
}
}
protected function unsetConfig(): void
{
foreach ($this->originalConfig as $key => $value) {
$this->config->set($key, $value);
}
}
}

View file

@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Stancl\Tenancy\Bootstrappers;
use Closure;
use Illuminate\Config\Repository;
use Illuminate\Contracts\Routing\UrlGenerator;
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
use Stancl\Tenancy\Contracts\Tenant;
class UrlTenancyBootstrapper implements TenancyBootstrapper
{
public static Closure|null $rootUrlOverride = null;
protected string|null $originalRootUrl = null;
public function __construct(
protected UrlGenerator $urlGenerator,
protected Repository $config,
) {
}
public function bootstrap(Tenant $tenant): void
{
$this->originalRootUrl = $this->urlGenerator->to('/');
if (static::$rootUrlOverride) {
$newRootUrl = (static::$rootUrlOverride)($tenant);
$this->urlGenerator->forceRootUrl($newRootUrl);
$this->config->set('app.url', $newRootUrl);
}
}
public function revert(): void
{
$this->urlGenerator->forceRootUrl($this->originalRootUrl);
$this->config->set('app.url', $this->originalRootUrl);
}
}

View file

@ -33,9 +33,8 @@ class ImpersonationToken extends Model
public $incrementing = false;
protected $table = 'tenant_user_impersonation_tokens';
protected $dates = [
'created_at',
protected $casts = [
'created_at' => 'datetime',
];
public static function booted(): void

View file

@ -32,6 +32,8 @@ class Tenant extends Model implements Contracts\Tenant
Concerns\InitializationHelpers,
Concerns\InvalidatesResolverCache;
protected static $modelsShouldPreventAccessingMissingAttributes = false;
protected $table = 'tenants';
protected $primaryKey = 'id';
protected $guarded = [];

View file

@ -41,7 +41,8 @@ class PermissionControlledMySQLDatabaseManager extends MySQLDatabaseManager impl
protected function isVersion8(): bool
{
$version = $this->database()->select($this->database()->raw('select version()'))[0]->{'version()'};
$versionSelect = (string) $this->database()->raw('select version()')->getValue($this->database()->getQueryGrammar());
$version = $this->database()->select($versionSelect)[0]->{'version()'};
return version_compare($version, '8.0.0') >= 0;
}

View file

@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace Stancl\Tenancy\Features;
use Illuminate\Foundation\Application;
use Stancl\Tenancy\Contracts\Feature;
use Stancl\Tenancy\Tenancy;
use Stancl\Tenancy\Vite;
class ViteBundler implements Feature
{
/** @var Application */
protected $app;
public function __construct(Application $app)
{
$this->app = $app;
}
public function bootstrap(Tenancy $tenancy): void
{
$this->app->singleton(\Illuminate\Foundation\Vite::class, Vite::class);
}
}

View file

@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace Stancl\Tenancy; // todo new Overrides namespace?
use Illuminate\Broadcasting\Broadcasters\Broadcaster;
use Illuminate\Broadcasting\BroadcastManager;
use Illuminate\Contracts\Broadcasting\Broadcaster as BroadcasterContract;
use Illuminate\Contracts\Foundation\Application;
class TenancyBroadcastManager extends BroadcastManager
{
/**
* Names of broadcasters to always recreate using $this->resolve() (even when they're
* cached and available in the $broadcasters property).
*
* The reason for recreating the broadcasters is
* to make your app use the correct broadcaster credentials when tenancy is initialized.
*/
public static array $tenantBroadcasters = ['pusher', 'ably'];
/**
* Override the get method so that the broadcasters in $tenantBroadcasters
* always get freshly resolved even when they're cached and available in the $broadcasters property,
* and that the resolved broadcaster will override the BroadcasterContract::class singleton.
*
* If there's a cached broadcaster with the same name as $name,
* give its channels to the newly resolved bootstrapper.
*/
protected function get($name)
{
if (in_array($name, static::$tenantBroadcasters)) {
/** @var Broadcaster|null $originalBroadcaster */
$originalBroadcaster = $this->app->make(BroadcasterContract::class);
$newBroadcaster = $this->resolve($name);
// If there is a current broadcaster, give its channels to the newly resolved one
// Broadcasters only have to implement the Illuminate\Contracts\Broadcasting\Broadcaster contract
// Which doesn't require the channels property
// So passing the channels is only needed for Illuminate\Broadcasting\Broadcasters\Broadcaster instances
if ($originalBroadcaster instanceof Broadcaster && $newBroadcaster instanceof Broadcaster) {
$this->passChannelsFromOriginalBroadcaster($originalBroadcaster, $newBroadcaster);
}
$this->app->singleton(BroadcasterContract::class, fn (Application $app) => $newBroadcaster);
return $newBroadcaster;
}
return parent::get($name);
}
// Because, unlike the original broadcaster, the newly resolved broadcaster won't have the channels registered using routes/channels.php
// Using it for broadcasting won't work, unless we make it have the original broadcaster's channels
protected function passChannelsFromOriginalBroadcaster(Broadcaster $originalBroadcaster, Broadcaster $newBroadcaster): void
{
// invade() because channels can't be retrieved through any of the broadcaster's public methods
$originalBroadcaster = invade($originalBroadcaster);
foreach ($originalBroadcaster->channels as $channel => $callback) {
$newBroadcaster->channel($channel, $callback, $originalBroadcaster->retrieveChannelOptions($channel));
}
}
}

View file

@ -63,6 +63,7 @@ class TenancyServiceProvider extends ServiceProvider
$this->app->singleton(Commands\Rollback::class, function ($app) {
return new Commands\Rollback($app['migrator']);
});
$this->app->singleton(Commands\Seed::class, function ($app) {
return new Commands\Seed($app['db']);
});

22
src/Vite.php Normal file
View file

@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace Stancl\Tenancy;
use Illuminate\Foundation\Vite as BaseVite;
class Vite extends BaseVite // todo move to a different directory in v4
{
/**
* Generate an asset path for the application.
*
* @param string $path
* @param bool|null $secure
* @return string
*/
protected function assetPath($path, $secure = null)
{
return global_asset($path);
}
}