1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2025-12-12 12:24:04 +00:00
This commit is contained in:
Samuel Štancl 2019-09-19 20:32:09 +02:00
parent cbaa775876
commit c9903cd43c
19 changed files with 212 additions and 215 deletions

View file

@ -13,14 +13,14 @@ class CacheManager extends BaseCacheManager
$tags = [config('tenancy.cache.tag_base') . tenant('id')]; $tags = [config('tenancy.cache.tag_base') . tenant('id')];
if ($method === 'tags') { if ($method === 'tags') {
if (\count($parameters) !== 1) { if (count($parameters) !== 1) {
throw new \Exception("Method tags() takes exactly 1 argument. {count($parameters)} passed."); throw new \Exception("Method tags() takes exactly 1 argument. {count($parameters)} passed.");
} }
$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/5.7/cache#removing-tagged-cache-items
return $this->store()->tags(\array_merge($tags, $names)); return $this->store()->tags(array_merge($tags, $names));
} }
return $this->store()->tags($tags)->$method(...$parameters); return $this->store()->tags($tags)->$method(...$parameters);

View file

@ -36,21 +36,21 @@ class Install extends Command
]); ]);
$this->info('✔️ Created config/tenancy.php'); $this->info('✔️ Created config/tenancy.php');
$newKernel = \str_replace( $newKernel = str_replace(
'protected $middlewarePriority = [', 'protected $middlewarePriority = [',
"protected \$middlewarePriority = [ "protected \$middlewarePriority = [
\Stancl\Tenancy\Middleware\PreventAccessFromTenantDomains::class, \Stancl\Tenancy\Middleware\PreventAccessFromTenantDomains::class,
\Stancl\Tenancy\Middleware\InitializeTenancy::class,", \Stancl\Tenancy\Middleware\InitializeTenancy::class,",
\file_get_contents(app_path('Http/Kernel.php')) file_get_contents(app_path('Http/Kernel.php'))
); );
$newKernel = \str_replace("'web' => [", "'web' => [ $newKernel = str_replace("'web' => [", "'web' => [
\Stancl\Tenancy\Middleware\PreventAccessFromTenantDomains::class,", $newKernel); \Stancl\Tenancy\Middleware\PreventAccessFromTenantDomains::class,", $newKernel);
\file_put_contents(app_path('Http/Kernel.php'), $newKernel); file_put_contents(app_path('Http/Kernel.php'), $newKernel);
$this->info('✔️ Set middleware priority'); $this->info('✔️ Set middleware priority');
\file_put_contents( file_put_contents(
base_path('routes/tenant.php'), base_path('routes/tenant.php'),
"<?php "<?php
@ -82,8 +82,8 @@ Route::get('/', function () {
$this->info('✔️ Created migration.'); $this->info('✔️ Created migration.');
} }
if (! \is_dir(database_path('migrations/tenant'))) { if (! is_dir(database_path('migrations/tenant'))) {
\mkdir(database_path('migrations/tenant')); mkdir(database_path('migrations/tenant'));
$this->info('✔️ Created database/migrations/tenant folder.'); $this->info('✔️ Created database/migrations/tenant folder.');
} }

View file

@ -39,7 +39,7 @@ class Run extends Command
$callback = function ($prefix = '') { $callback = function ($prefix = '') {
return function ($arguments, $argument) use ($prefix) { return function ($arguments, $argument) use ($prefix) {
[$key, $value] = \explode('=', $argument, 2); [$key, $value] = explode('=', $argument, 2);
$arguments[$prefix . $key] = $value; $arguments[$prefix . $key] = $value;
return $arguments; return $arguments;
@ -47,13 +47,13 @@ class Run extends Command
}; };
// Turns ['foo=bar', 'abc=xyz=zzz'] into ['foo' => 'bar', 'abc' => 'xyz=zzz'] // Turns ['foo=bar', 'abc=xyz=zzz'] into ['foo' => 'bar', 'abc' => 'xyz=zzz']
$arguments = \array_reduce($this->option('argument'), $callback(), []); $arguments = array_reduce($this->option('argument'), $callback(), []);
// Turns ['foo=bar', 'abc=xyz=zzz'] into ['--foo' => 'bar', '--abc' => 'xyz=zzz'] // Turns ['foo=bar', 'abc=xyz=zzz'] into ['--foo' => 'bar', '--abc' => 'xyz=zzz']
$options = \array_reduce($this->option('option'), $callback('--'), []); $options = array_reduce($this->option('option'), $callback('--'), []);
// Run command // Run command
$this->call($this->argument('commandname'), \array_merge($arguments, $options)); $this->call($this->argument('commandname'), array_merge($arguments, $options));
tenancy()->endTenancy(); tenancy()->endTenancy();
}); });

View file

@ -8,7 +8,7 @@ use Stancl\Tenancy\Tenant;
interface TenancyBootstrapper interface TenancyBootstrapper
{ {
public function start(Tenant $tenant); // todo2 TenantManager instead of Tenant public function start(Tenant $tenant);
public function end(); public function end();
} }

View file

@ -26,7 +26,7 @@ class TelescopeTags implements Feature
if (in_array('tenancy', optional(request()->route())->middleware() ?? [])) { if (in_array('tenancy', optional(request()->route())->middleware() ?? [])) {
$tags = array_merge($tags, [ $tags = array_merge($tags, [
'tenant:' . tenant('id'), 'tenant:' . tenant('id'),
// todo2 domain? // todo3 domain?
]); ]);
} }

View file

@ -19,8 +19,8 @@ class PreventAccessFromTenantDomains
{ {
// If the domain is not in exempt domains, it's a tenant domain. // If the domain is not in exempt domains, it's a tenant domain.
// Tenant domains can't have routes without tenancy middleware. // Tenant domains can't have routes without tenancy middleware.
if (! \in_array(request()->getHost(), config('tenancy.exempt_domains')) && if (! in_array(request()->getHost(), config('tenancy.exempt_domains')) &&
! \in_array('tenancy', request()->route()->middleware())) { ! in_array('tenancy', request()->route()->middleware())) {
abort(404); abort(404);
} }

View file

@ -39,7 +39,7 @@ class FilesystemTenancyBootstrapper implements TenancyBootstrapper
foreach ($this->app['config']['tenancy.filesystem.disks'] as $disk) { foreach ($this->app['config']['tenancy.filesystem.disks'] as $disk) {
$this->originalPaths['disks'][$disk] = Storage::disk($disk)->getAdapter()->getPathPrefix(); $this->originalPaths['disks'][$disk] = Storage::disk($disk)->getAdapter()->getPathPrefix();
if ($root = \str_replace('%storage_path%', storage_path(), $this->app['config']["tenancy.filesystem.root_override.{$disk}"])) { if ($root = str_replace('%storage_path%', storage_path(), $this->app['config']["tenancy.filesystem.root_override.{$disk}"])) {
Storage::disk($disk)->getAdapter()->setPathPrefix($root); Storage::disk($disk)->getAdapter()->setPathPrefix($root);
} else { } else {
$root = $this->app['config']["filesystems.disks.{$disk}.root"]; $root = $this->app['config']["filesystems.disks.{$disk}.root"];

View file

@ -22,7 +22,7 @@ class QueueTenancyBootstrapper implements TenancyBootstrapper
$this->app['queue']->createPayloadUsing([$this, 'createPayload']); $this->app['queue']->createPayloadUsing([$this, 'createPayload']);
$this->app['events']->listen(\Illuminate\Queue\Events\JobProcessing::class, function ($event) { $this->app['events']->listen(\Illuminate\Queue\Events\JobProcessing::class, function ($event) {
if (\array_key_exists('tenant_id', $event->job->payload())) { if (array_key_exists('tenant_id', $event->job->payload())) {
tenancy()->initById($event->job->payload()['tenant_id']); tenancy()->initById($event->job->payload()['tenant_id']);
} }
}); });
@ -50,7 +50,7 @@ class QueueTenancyBootstrapper implements TenancyBootstrapper
'tenant_id' => $id, 'tenant_id' => $id,
'tags' => [ 'tags' => [
"tenant:$id", "tenant:$id",
// todo2 domain // todo3 domain
], ],
]; ];
} }

View file

@ -11,7 +11,6 @@ use Stancl\Tenancy\Contracts\UniqueIdentifierGenerator;
use Stancl\Tenancy\Exceptions\TenantStorageException; use Stancl\Tenancy\Exceptions\TenantStorageException;
// todo2 write tests for updating the tenant // todo2 write tests for updating the tenant
// todo2 addDomain(), removeDomain()
/** /**
* @internal Class is subject to breaking changes in minor and patch versions. * @internal Class is subject to breaking changes in minor and patch versions.

View file

@ -11,8 +11,8 @@ class TenantRouteServiceProvider extends RouteServiceProvider
{ {
public function map() public function map()
{ {
if (! \in_array(request()->getHost(), $this->app['config']['tenancy.exempt_domains'] ?? []) if (! in_array(request()->getHost(), $this->app['config']['tenancy.exempt_domains'] ?? [])
&& \file_exists(base_path('routes/tenant.php'))) { && file_exists(base_path('routes/tenant.php'))) {
Route::middleware(['web', 'tenancy']) Route::middleware(['web', 'tenancy'])
->namespace($this->app['config']['tenant_route_namespace'] ?? 'App\Http\Controllers') ->namespace($this->app['config']['tenant_route_namespace'] ?? 'App\Http\Controllers')
->group(base_path('routes/tenant.php')); ->group(base_path('routes/tenant.php'));

View file

@ -10,7 +10,7 @@ trait HasATenantsOption
{ {
protected function getOptions() protected function getOptions()
{ {
return \array_merge([ return array_merge([
['tenants', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_OPTIONAL, '', null], ['tenants', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_OPTIONAL, '', null],
], parent::getOptions()); ], parent::getOptions());
} }

View file

@ -122,95 +122,14 @@ class CommandsTest extends TestCase
/** @test */ /** @test */
public function install_command_works() public function install_command_works()
{ {
if (! \is_dir($dir = app_path('Http'))) { if (! is_dir($dir = app_path('Http'))) {
\mkdir($dir, 0777, true); mkdir($dir, 0777, true);
} }
if (! \is_dir($dir = base_path('routes'))) { if (! is_dir($dir = base_path('routes'))) {
\mkdir($dir, 0777, true); mkdir($dir, 0777, true);
} }
// todo2 move this to a file file_put_contents(app_path('Http/Kernel.php'), file_get_contents(__DIR__ . '/Etc/defaultHttpKernel.stub'));
\file_put_contents(app_path('Http/Kernel.php'), "<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected \$middleware = [
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected \$middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected \$routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
/**
* The priority-sorted list of middleware.
*
* This forces non-global middleware to always be in the given order.
*
* @var array
*/
protected \$middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\Authenticate::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
];
}
");
$this->artisan('tenancy:install') $this->artisan('tenancy:install')
->expectsQuestion('Do you want to publish the default database migration?', 'yes'); ->expectsQuestion('Do you want to publish the default database migration?', 'yes');
@ -218,89 +137,6 @@ class Kernel extends HttpKernel
$this->assertFileExists(base_path('config/tenancy.php')); $this->assertFileExists(base_path('config/tenancy.php'));
$this->assertFileExists(database_path('migrations/2019_08_08_000000_create_tenants_table.php')); $this->assertFileExists(database_path('migrations/2019_08_08_000000_create_tenants_table.php'));
$this->assertDirectoryExists(database_path('migrations/tenant')); $this->assertDirectoryExists(database_path('migrations/tenant'));
$this->assertSame("<?php $this->assertSame(file_get_contents(__DIR__ . '/Etc/modifiedHttpKernel.stub'), file_get_contents(app_path('Http/Kernel.php')));
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected \$middleware = [
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected \$middlewareGroups = [
'web' => [
\Stancl\Tenancy\Middleware\PreventAccessFromTenantDomains::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected \$routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
/**
* The priority-sorted list of middleware.
*
* This forces non-global middleware to always be in the given order.
*
* @var array
*/
protected \$middlewarePriority = [
\Stancl\Tenancy\Middleware\PreventAccessFromTenantDomains::class,
\Stancl\Tenancy\Middleware\InitializeTenancy::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\Authenticate::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
];
}
", \file_get_contents(app_path('Http/Kernel.php')));
} }
} }

View file

@ -0,0 +1,80 @@
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
/**
* The priority-sorted list of middleware.
*
* This forces non-global middleware to always be in the given order.
*
* @var array
*/
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\Authenticate::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
];
}

View file

@ -0,0 +1,83 @@
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\Stancl\Tenancy\Middleware\PreventAccessFromTenantDomains::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
/**
* The priority-sorted list of middleware.
*
* This forces non-global middleware to always be in the given order.
*
* @var array
*/
protected $middlewarePriority = [
\Stancl\Tenancy\Middleware\PreventAccessFromTenantDomains::class,
\Stancl\Tenancy\Middleware\InitializeTenancy::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\Authenticate::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
];
}

View file

@ -56,6 +56,6 @@ class TestJob implements ShouldQueue
*/ */
public function handle() public function handle()
{ {
logger(\json_encode(\DB::table('users')->get())); logger(json_encode(DB::table('users')->get()));
} }
} }

View file

@ -28,10 +28,10 @@ class ReidentificationTest extends TestCase
foreach (config('tenancy.filesystem.disks') as $disk) { foreach (config('tenancy.filesystem.disks') as $disk) {
$suffix = config('tenancy.filesystem.suffix_base') . tenant('id'); $suffix = config('tenancy.filesystem.suffix_base') . tenant('id');
$current_path_prefix = \Storage::disk($disk)->getAdapter()->getPathPrefix(); $current_path_prefix = Storage::disk($disk)->getAdapter()->getPathPrefix();
if ($override = config("tenancy.filesystem.root_override.{$disk}")) { if ($override = config("tenancy.filesystem.root_override.{$disk}")) {
$correct_path_prefix = \str_replace('%storage_path%', storage_path(), $override); $correct_path_prefix = str_replace('%storage_path%', storage_path(), $override);
} else { } else {
if ($base = $originals[$disk]) { if ($base = $originals[$disk]) {
$correct_path_prefix = $base . "/$suffix/"; $correct_path_prefix = $base . "/$suffix/";

View file

@ -6,8 +6,7 @@ namespace Stancl\Tenancy\Tests;
use Illuminate\Support\Facades\Redis; use Illuminate\Support\Facades\Redis;
// todo2 rename class TenancyBootstrappersTest extends TestCase
class BootstrapsTenancyTest extends TestCase
{ {
public $autoInitTenancy = false; public $autoInitTenancy = false;
@ -53,10 +52,10 @@ class BootstrapsTenancyTest extends TestCase
foreach (config('tenancy.filesystem.disks') as $disk) { foreach (config('tenancy.filesystem.disks') as $disk) {
$suffix = config('tenancy.filesystem.suffix_base') . tenant('id'); $suffix = config('tenancy.filesystem.suffix_base') . tenant('id');
$current_path_prefix = \Storage::disk($disk)->getAdapter()->getPathPrefix(); $current_path_prefix = Storage::disk($disk)->getAdapter()->getPathPrefix();
if ($override = config("tenancy.filesystem.root_override.{$disk}")) { if ($override = config("tenancy.filesystem.root_override.{$disk}")) {
$correct_path_prefix = \str_replace('%storage_path%', storage_path(), $override); $correct_path_prefix = str_replace('%storage_path%', storage_path(), $override);
} else { } else {
if ($base = $old_storage_facade_roots[$disk]) { if ($base = $old_storage_facade_roots[$disk]) {
$correct_path_prefix = $base . "/$suffix/"; $correct_path_prefix = $base . "/$suffix/";

View file

@ -95,20 +95,20 @@ class TenantStorageTest extends TestCase
public function data_is_stored_with_correct_data_types() public function data_is_stored_with_correct_data_types()
{ {
tenant()->put('someBool', false); tenant()->put('someBool', false);
$this->assertSame('boolean', \gettype(tenant()->get('someBool'))); $this->assertSame('boolean', gettype(tenant()->get('someBool')));
$this->assertSame('boolean', \gettype(tenant()->get(['someBool'])['someBool'])); $this->assertSame('boolean', gettype(tenant()->get(['someBool'])['someBool']));
tenant()->put('someInt', 5); tenant()->put('someInt', 5);
$this->assertSame('integer', \gettype(tenant()->get('someInt'))); $this->assertSame('integer', gettype(tenant()->get('someInt')));
$this->assertSame('integer', \gettype(tenant()->get(['someInt'])['someInt'])); $this->assertSame('integer', gettype(tenant()->get(['someInt'])['someInt']));
tenant()->put('someDouble', 11.40); tenant()->put('someDouble', 11.40);
$this->assertSame('double', \gettype(tenant()->get('someDouble'))); $this->assertSame('double', gettype(tenant()->get('someDouble')));
$this->assertSame('double', \gettype(tenant()->get(['someDouble'])['someDouble'])); $this->assertSame('double', gettype(tenant()->get(['someDouble'])['someDouble']));
tenant()->put('string', 'foo'); tenant()->put('string', 'foo');
$this->assertSame('string', \gettype(tenant()->get('string'))); $this->assertSame('string', gettype(tenant()->get('string')));
$this->assertSame('string', \gettype(tenant()->get(['string'])['string'])); $this->assertSame('string', gettype(tenant()->get(['string'])['string']));
} }
/** @test */ /** @test */
@ -159,6 +159,6 @@ class TenantStorageTest extends TestCase
tenant()->put(['foo' => 'bar', 'abc' => 'xyz']); tenant()->put(['foo' => 'bar', 'abc' => 'xyz']);
$this->assertSame(['bar', 'xyz'], tenant()->get(['foo', 'abc'])); $this->assertSame(['bar', 'xyz'], tenant()->get(['foo', 'abc']));
$this->assertSame('bar', \DB::connection('central')->table('tenants')->where('id', tenant('id'))->first()->foo); $this->assertSame('bar', DB::connection('central')->table('tenants')->where('id', tenant('id'))->first()->foo);
} }
} }

View file

@ -27,7 +27,7 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase
Redis::connection('cache')->flushdb(); Redis::connection('cache')->flushdb();
$this->loadMigrationsFrom([ $this->loadMigrationsFrom([
'--path' => \realpath(__DIR__ . '/../assets/migrations'), '--path' => realpath(__DIR__ . '/../assets/migrations'),
'--database' => 'central', '--database' => 'central',
]); ]);
config(['database.default' => 'sqlite']); // fix issue caused by loadMigrationsFrom config(['database.default' => 'sqlite']); // fix issue caused by loadMigrationsFrom
@ -59,11 +59,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(); \Dotenv\Dotenv::create(__DIR__ . '/..')->load();
} }
\fclose(\fopen(database_path('central.sqlite'), 'w')); fclose(fopen(database_path('central.sqlite'), 'w'));
$app['config']->set([ $app['config']->set([
'database.redis.cache.host' => env('TENANCY_TEST_REDIS_HOST', '127.0.0.1'), 'database.redis.cache.host' => env('TENANCY_TEST_REDIS_HOST', '127.0.0.1'),
@ -152,7 +152,7 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase
public function randomString(int $length = 10) public function randomString(int $length = 10)
{ {
return \substr(\str_shuffle(\str_repeat($x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', (int) (\ceil($length / \strlen($x))))), 1, $length); return substr(str_shuffle(str_repeat($x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', (int) (ceil($length / strlen($x))))), 1, $length);
} }
public function isContainerized() public function isContainerized()
@ -162,6 +162,6 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase
public function assertArrayIsSubset($subset, $array, string $message = ''): void public function assertArrayIsSubset($subset, $array, string $message = ''): void
{ {
parent::assertTrue(\array_intersect($subset, $array) == $subset, $message); parent::assertTrue(array_intersect($subset, $array) == $subset, $message);
} }
} }