1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2026-02-05 21:34:03 +00:00

Merge branch 'master' into stein-j-readied-tenant

This commit is contained in:
lukinovec 2022-07-22 09:27:52 +02:00 committed by GitHub
commit 095c2e1380
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
55 changed files with 556 additions and 123 deletions

View file

@ -2,12 +2,14 @@ name: CI
env:
COMPOSE_INTERACTIVE_NO_CLI: 1
PHP_CS_FIXER_IGNORE_ENV: 1
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
on:
push:
branches: [ 3.x, 2.x, master ]
branches: [ master ]
pull_request:
branches: [ 3.x, 2.x, master ]
branches: [ master ]
jobs:
tests:
@ -15,11 +17,8 @@ jobs:
strategy:
matrix:
php: ["7.3", "8.0"]
laravel: ["^6.0", "^8.0", "^9.0"]
exclude:
- laravel: "^9.0"
php: "7.3"
php: ["8.1"]
laravel: ["^9.0"]
steps:
- uses: actions/checkout@v2
@ -29,3 +28,19 @@ jobs:
run: docker-compose exec -T test composer require --no-interaction "laravel/framework:${{ matrix.laravel }}"
- name: Run tests
run: ./test
php-cs-fixer:
name: Code style (php-cs-fixer)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install php-cs-fixer
run: composer global require friendsofphp/php-cs-fixer
- name: Run php-cs-fixer
run: $HOME/.composer/vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.php
- name: Commit changes from php-cs-fixer
uses: EndBug/add-and-commit@v5
with:
author_name: "PHP CS Fixer"
author_email: "phpcsfixer@example.com"
message: Fix code style (php-cs-fixer)

2
.gitignore vendored
View file

@ -9,5 +9,7 @@ psysh
phpunit_var_*.xml
coverage/
clover.xml
tenant-schema-test.dump
tests/Etc/tmp/queuetest.json
docker-compose.override.yml
.php-cs-fixer.cache

141
.php-cs-fixer.php Normal file
View file

@ -0,0 +1,141 @@
<?php
use PhpCsFixer\Config;
use PhpCsFixer\Finder;
$rules = [
'array_syntax' => ['syntax' => 'short'],
'binary_operator_spaces' => [
'default' => 'single_space',
'operators' => [
'=>' => null,
'|' => 'no_space',
]
],
'blank_line_after_namespace' => true,
'blank_line_after_opening_tag' => true,
'no_superfluous_phpdoc_tags' => true,
'blank_line_before_statement' => [
'statements' => ['return']
],
'braces' => true,
'cast_spaces' => true,
'class_definition' => true,
'concat_space' => [
'spacing' => 'one'
],
'declare_equal_normalize' => true,
'elseif' => true,
'encoding' => true,
'full_opening_tag' => true,
'declare_strict_types' => true,
'fully_qualified_strict_types' => true, // added by Shift
'function_declaration' => true,
'function_typehint_space' => true,
'heredoc_to_nowdoc' => true,
'include' => true,
'increment_style' => ['style' => 'post'],
'indentation_type' => true,
'linebreak_after_opening_tag' => true,
'line_ending' => true,
'lowercase_cast' => true,
'constant_case' => true,
'lowercase_keywords' => true,
'lowercase_static_reference' => true, // added from Symfony
'magic_method_casing' => true, // added from Symfony
'magic_constant_casing' => true,
'method_argument_space' => true,
'native_function_casing' => true,
'no_alias_functions' => true,
'no_extra_blank_lines' => [
'tokens' => [
'extra',
'throw',
'use',
'use_trait',
]
],
'no_blank_lines_after_class_opening' => true,
'no_blank_lines_after_phpdoc' => true,
'no_closing_tag' => true,
'no_empty_phpdoc' => true,
'no_empty_statement' => true,
'no_leading_import_slash' => true,
'no_leading_namespace_whitespace' => true,
'no_mixed_echo_print' => [
'use' => 'echo'
],
'no_multiline_whitespace_around_double_arrow' => true,
'multiline_whitespace_before_semicolons' => [
'strategy' => 'no_multi_line'
],
'no_short_bool_cast' => true,
'no_singleline_whitespace_before_semicolons' => true,
'no_spaces_after_function_name' => true,
'no_spaces_around_offset' => true,
'no_spaces_inside_parenthesis' => true,
'no_trailing_comma_in_list_call' => true,
'no_trailing_comma_in_singleline_array' => true,
'no_trailing_whitespace' => true,
'no_trailing_whitespace_in_comment' => true,
'no_unneeded_control_parentheses' => true,
'no_unreachable_default_argument_value' => true,
'no_useless_return' => true,
'no_whitespace_before_comma_in_array' => true,
'no_whitespace_in_blank_line' => true,
'normalize_index_brace' => true,
'not_operator_with_successor_space' => true,
'object_operator_without_whitespace' => true,
'ordered_imports' => ['sort_algorithm' => 'alpha'],
'phpdoc_indent' => true,
'general_phpdoc_tag_rename' => true,
'phpdoc_no_access' => true,
'phpdoc_no_package' => true,
'phpdoc_no_useless_inheritdoc' => true,
'phpdoc_scalar' => true,
'phpdoc_single_line_var_spacing' => true,
'phpdoc_summary' => true,
'phpdoc_to_comment' => false,
'phpdoc_trim' => true,
'phpdoc_types' => true,
'phpdoc_var_without_name' => true,
'psr_autoloading' => true,
'self_accessor' => true,
'short_scalar_cast' => true,
'simplified_null_return' => false, // disabled by Shift
'single_blank_line_at_eof' => true,
'single_blank_line_before_namespace' => true,
'single_class_element_per_statement' => true,
'single_import_per_statement' => true,
'single_line_after_imports' => true,
'no_unused_imports' => true,
'single_line_comment_style' => [
'comment_types' => ['hash']
],
'single_quote' => true,
'space_after_semicolon' => true,
'standardize_not_equals' => true,
'switch_case_semicolon_to_colon' => true,
'switch_case_space' => true,
'ternary_operator_spaces' => true,
'trailing_comma_in_multiline' => true,
'trim_array_spaces' => true,
'unary_operator_spaces' => true,
'whitespace_after_comma_in_array' => true,
];
$project_path = getcwd();
$finder = Finder::create()
->in([
$project_path . '/src',
])
->name('*.php')
->notName('*.blade.php')
->ignoreDotFiles(true)
->ignoreVCS(true);
return (new Config())
->setFinder($finder)
->setRules($rules)
->setRiskyAllowed(true)
->setUsingCache(true);

View file

@ -1,7 +0,0 @@
risky: true
preset: laravel
enabled:
- declare_strict_types
disabled:
- concat_without_spaces
- ternary_operator_spaces

View file

@ -1,7 +1,7 @@
ARG PHP_VERSION=7.4
ARG PHP_TARGET=php:${PHP_VERSION}-cli
FROM ${PHP_TARGET}
FROM --platform=linux/amd64 ${PHP_TARGET}
ARG COMPOSER_TARGET=2.0.3
@ -22,10 +22,16 @@ ENV LANG=en_GB.UTF-8
# Dockerfile _and pin the versions_! Eg:
# RUN pecl install memcached-2.2.0 && docker-php-ext-enable memcached
# install some OS packages we need
RUN apt-get update
RUN apt-get install -y --no-install-recommends libfreetype6-dev libjpeg62-turbo-dev libpng-dev libgmp-dev libldap2-dev netcat curl sqlite3 libsqlite3-dev libpq-dev libzip-dev unzip vim-tiny gosu git
# install php extensions
RUN apt-get update \
&& apt-get install -y gnupg2 \
&& curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - \
&& curl https://packages.microsoft.com/config/debian/11/prod.list > /etc/apt/sources.list.d/mssql-release.list \
&& apt-get update \
&& ACCEPT_EULA=Y apt-get install -y unixodbc-dev msodbcsql17
RUN apt-get install -y --no-install-recommends locales apt-transport-https libfreetype6-dev libjpeg62-turbo-dev libpng-dev libgmp-dev libldap2-dev netcat curl mariadb-client sqlite3 libsqlite3-dev libpq-dev libzip-dev unzip vim-tiny gosu git
RUN docker-php-ext-configure pgsql -with-pgsql=/usr/local/pgsql \
# && if [ "${PHP_VERSION}" = "7.4" ]; then docker-php-ext-configure gd --with-freetype --with-jpeg; else docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/; fi \
&& docker-php-ext-install -j$(nproc) gd pdo pdo_mysql pdo_pgsql pdo_sqlite pgsql zip gmp bcmath pcntl ldap sysvmsg exif \
@ -35,7 +41,10 @@ RUN docker-php-ext-configure pgsql -with-pgsql=/usr/local/pgsql \
# install the pcov extention
&& pecl install pcov \
&& docker-php-ext-enable pcov \
&& echo "pcov.enabled = 1" > /usr/local/etc/php/conf.d/pcov.ini
&& echo "pcov.enabled = 1" > /usr/local/etc/php/conf.d/pcov.ini \
# install sqlsrv
&& pecl install sqlsrv pdo_sqlsrv \
&& docker-php-ext-enable sqlsrv pdo_sqlsrv
# clear the apt cache
RUN rm -rf /var/lib/apt/lists/* \
&& rm -rf /var/lib/apt/lists/* \

View file

@ -1,5 +1,5 @@
# Get Support
If you need help with implementing the package, you can join our community [Discord server](https://discord.gg/7cpgPxv) and ask in `#help`.
If you need help with implementing the package, you can join our community [Discord server](https://archte.ch/discord) and ask in `#help`.
If you're interested in paid consulting from the maintainer, see the [contact page](https://tenancyforlaravel.com/contact/) on our website.

View file

@ -40,7 +40,13 @@ class TenancyServiceProvider extends ServiceProvider
Events\TenantSaved::class => [],
Events\UpdatingTenant::class => [],
Events\TenantUpdated::class => [],
Events\DeletingTenant::class => [],
Events\DeletingTenant::class => [
JobPipeline::make([
Jobs\DeleteDomains::class,
])->send(function (Events\DeletingTenant $event) {
return $event->tenant;
})->shouldBeQueued(false),
],
Events\TenantDeleted::class => [
JobPipeline::make([
Jobs\DeleteDatabase::class,

View file

@ -92,6 +92,7 @@ return [
'sqlite' => Stancl\Tenancy\TenantDatabaseManagers\SQLiteDatabaseManager::class,
'mysql' => Stancl\Tenancy\TenantDatabaseManagers\MySQLDatabaseManager::class,
'pgsql' => Stancl\Tenancy\TenantDatabaseManagers\PostgreSQLDatabaseManager::class,
'sqlsrv' => Stancl\Tenancy\TenantDatabaseManagers\MicrosoftSQLDatabaseManager::class,
/**
* Use this database manager for MySQL to have a DB user created for each tenant database.

View file

@ -21,7 +21,7 @@ class CreateDomainsTable extends Migration
$table->string('tenant_id');
$table->timestamps();
$table->foreign('tenant_id')->references('id')->on('tenants')->onUpdate('cascade')->onDelete('cascade');
$table->foreign('tenant_id')->references('id')->on('tenants')->onUpdate('cascade');
});
}

View file

@ -20,6 +20,7 @@
"require-dev": {
"laravel/framework": "^6.0|^7.0|^8.0|^9.0",
"orchestra/testbench": "^4.0|^5.0|^6.0|^7.0",
"phpunit/phpunit": "*",
"league/flysystem-aws-s3-v3": "^1.0|^3.0",
"doctrine/dbal": "^2.10",
"spatie/valuestore": "^1.2.5"

View file

@ -22,6 +22,9 @@ services:
TENANCY_TEST_REDIS_HOST: redis
TENANCY_TEST_MYSQL_HOST: mysql
TENANCY_TEST_PGSQL_HOST: postgres
TENANCY_TEST_SQLSRV_HOST: mssql
TENANCY_TEST_SQLSRV_USERNAME: sa
TENANCY_TEST_SQLSRV_PASSWORD: P@ssword
stdin_open: true
tty: true
mysql:
@ -64,3 +67,11 @@ services:
interval: 1s
timeout: 3s
retries: 30
mssql:
image: mcr.microsoft.com/mssql/server:2019-latest
ports:
- 1433:1433
environment:
- ACCEPT_EULA=Y
- SA_PASSWORD=P@ssword # todo reuse values from env above
# todo missing health check

View file

@ -69,7 +69,7 @@ class FilesystemTenancyBootstrapper implements TenancyBootstrapper
if (! $finalPrefix) {
$finalPrefix = $originalRoot
? rtrim($originalRoot, '/') . '/'. $suffix
? rtrim($originalRoot, '/') . '/' . $suffix
: $suffix;
}

View file

@ -4,18 +4,17 @@ declare(strict_types=1);
namespace Stancl\Tenancy\Bootstrappers;
use Illuminate\Support\Str;
use Illuminate\Config\Repository;
use Illuminate\Queue\QueueManager;
use Stancl\Tenancy\Contracts\Tenant;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Contracts\Foundation\Application;
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\Queue\QueueManager;
use Illuminate\Support\Testing\Fakes\QueueFake;
use Illuminate\Contracts\Foundation\Application;
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
use Stancl\Tenancy\Contracts\Tenant;
class QueueTenancyBootstrapper implements TenancyBootstrapper
{

View file

@ -13,7 +13,6 @@ class CacheManager extends BaseCacheManager
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
@ -21,7 +20,7 @@ class CacheManager extends BaseCacheManager
if ($method === 'tags') {
$count = count($parameters);
if ($count !== 1) {
throw new \Exception("Method tags() takes exactly 1 argument. $count passed.");
}

View file

@ -24,8 +24,6 @@ class Install extends Command
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{

View file

@ -33,8 +33,6 @@ class Migrate extends MigrateCommand
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{

View file

@ -31,8 +31,6 @@ final class MigrateFresh extends Command
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{

View file

@ -42,8 +42,6 @@ class Rollback extends RollbackCommand
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{

View file

@ -28,8 +28,6 @@ class Run extends Command
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{

View file

@ -35,8 +35,6 @@ class Seed extends SeedCommand
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{

View file

@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace Stancl\Tenancy\Commands;
use Illuminate\Console\Command;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Database\ConnectionResolverInterface;
use Illuminate\Database\Console\DumpCommand;
use Stancl\Tenancy\Contracts\Tenant;
use Symfony\Component\Console\Input\InputOption;
class TenantDump extends DumpCommand
{
public function __construct()
{
parent::__construct();
$this->setName('tenants:dump');
$this->specifyParameters();
}
public function handle(ConnectionResolverInterface $connections, Dispatcher $dispatcher): int
{
$this->tenant()->run(fn () => parent::handle($connections, $dispatcher));
return Command::SUCCESS;
}
public function tenant(): Tenant
{
$tenant = $this->option('tenant')
?? tenant()
?? $this->ask('What tenant do you want to dump the schema for?')
?? tenancy()->query()->first();
if (! $tenant instanceof Tenant) {
$tenant = tenancy()->find($tenant);
}
throw_if(! $tenant, 'Could not identify the tenant to use for dumping the schema.');
return $tenant;
}
protected function getOptions(): array
{
return array_merge([
['tenant', null, InputOption::VALUE_OPTIONAL, '', null],
], parent::getOptions());
}
}

View file

@ -25,8 +25,6 @@ class TenantList extends Command
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{

View file

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace Stancl\Tenancy\Concerns;
trait ExtendsLaravelCommand

View file

@ -20,18 +20,11 @@ interface TenantDatabaseManager
/**
* Does a database exist.
*
* @param string $name
* @return bool
*/
public function databaseExists(string $name): bool;
/**
* Make a DB connection config array.
*
* @param array $baseConfig
* @param string $databaseName
* @return array
*/
public function makeConnectionConfig(array $baseConfig, string $databaseName): array;
@ -39,9 +32,6 @@ interface TenantDatabaseManager
* Set the DB connection that should be used by the tenant database manager.
*
* @throws NoConnectionSetException
*
* @param string $connection
* @return void
*/
public function setConnection(string $connection): void;
}

View file

@ -11,9 +11,6 @@ trait TenantRun
/**
* Run a callback in this tenant's context.
* Atomic, safely reverts to previous context.
*
* @param callable $callback
* @return mixed
*/
public function run(callable $callback)
{

View file

@ -22,10 +22,15 @@ class ImpersonationToken extends Model
use CentralConnection;
protected $guarded = [];
public $timestamps = false;
protected $primaryKey = 'token';
public $incrementing = false;
protected $table = 'tenant_user_impersonation_tokens';
protected $dates = [
'created_at',
];

View file

@ -30,7 +30,9 @@ class Tenant extends Model implements Contracts\Tenant
Concerns\HasPending;
protected $table = 'tenants';
protected $primaryKey = 'id';
protected $guarded = [];
public function getTenantKeyName(): string

View file

@ -80,8 +80,6 @@ class DatabaseConfig
/**
* Generate DB name, username & password and write them to the tenant model.
*
* @return void
*/
public function makeCredentials(): void
{
@ -113,7 +111,8 @@ class DatabaseConfig
$templateConnection = config("database.connections.{$template}");
return $this->manager()->makeConnectionConfig(
array_merge($templateConnection, $this->tenantConfig()), $this->getName()
array_merge($templateConnection, $this->tenantConfig()),
$this->getName()
);
}

View file

@ -33,7 +33,6 @@ class UserImpersonation implements Feature
*
* @param string|ImpersonationToken $token
* @param int $ttl
* @return RedirectResponse
*/
public static function makeResponse($token, int $ttl = null): RedirectResponse
{

View file

@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace Stancl\Tenancy\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Stancl\Tenancy\Contracts\TenantWithDatabase;
class DeleteDomains
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/** @var TenantWithDatabase */
protected $tenant;
public function __construct(TenantWithDatabase $tenant)
{
$this->tenant = $tenant;
}
public function handle()
{
$this->tenant->domains->each->delete();
}
}

View file

@ -48,8 +48,7 @@ class UpdateSyncedResource extends QueueableListener
protected function updateResourceInCentralDatabaseAndGetTenants($event, $syncedAttributes)
{
/** @var Model|SyncMaster $centralModel */
$centralModel = $event->model->getCentralModelName()
::where($event->model->getGlobalIdentifierKeyName(), $event->model->getGlobalIdentifierKey())
$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.

View file

@ -5,10 +5,10 @@ declare(strict_types=1);
namespace Stancl\Tenancy\Middleware;
use Closure;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode;
use Stancl\Tenancy\Exceptions\TenancyNotInitializedException;
use Symfony\Component\HttpFoundation\IpUtils;
use Symfony\Component\HttpKernel\Exception\HttpException;
class CheckTenantForMaintenanceMode extends CheckForMaintenanceMode
{

View file

@ -29,13 +29,13 @@ class InitializeTenancyByDomain extends IdentificationMiddleware
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $this->initializeTenancy(
$request, $next, $request->getHost()
$request,
$next,
$request->getHost()
);
}
}

View file

@ -13,8 +13,6 @@ class InitializeTenancyByDomainOrSubdomain
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{

View file

@ -38,7 +38,9 @@ class InitializeTenancyByPath extends IdentificationMiddleware
// simply injected into some route controller action.
if ($route->parameterNames()[0] === PathTenantResolver::$tenantParameterName) {
return $this->initializeTenancy(
$request, $next, $route
$request,
$next,
$route
);
} else {
throw new RouteIsMissingTenantParameterException;

View file

@ -36,8 +36,6 @@ class InitializeTenancyByRequestData extends IdentificationMiddleware
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{

View file

@ -28,8 +28,6 @@ class InitializeTenancyBySubdomain extends InitializeTenancyByDomain
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{

View file

@ -75,7 +75,6 @@ abstract class CachedTenantResolver implements TenantResolver
/**
* Get all the arg combinations for resolve() that can be used to find this tenant.
*
* @param Tenant $tenant
* @return array[]
*/
abstract public function getArgsForTenant(Tenant $tenant): array;

View file

@ -28,7 +28,6 @@ class Tenancy
/**
* Initializes the tenant.
* @param Tenant|int|string $tenant
* @return void
*/
public function initialize($tenant): void
{
@ -107,9 +106,6 @@ class Tenancy
/**
* Run a callback in the central context.
* Atomic, safely reverts to previous context.
*
* @param callable $callback
* @return mixed
*/
public function central(callable $callback)
{
@ -133,7 +129,6 @@ class Tenancy
* More performant than running $tenant->run() one by one.
*
* @param Tenant[]|\Traversable|string[]|null $tenants
* @param callable $callback
* @return void
*/
public function runForMultiple($tenants, callable $callback, bool $withPending = null)

View file

@ -15,8 +15,6 @@ class TenancyServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register(): void
{
@ -76,8 +74,6 @@ class TenancyServiceProvider extends ServiceProvider
/**
* Bootstrap services.
*
* @return void
*/
public function boot(): void
{
@ -88,6 +84,7 @@ class TenancyServiceProvider extends ServiceProvider
Commands\Migrate::class,
Commands\Rollback::class,
Commands\TenantList::class,
Commands\TenantDump::class,
Commands\MigrateFresh::class,
Commands\CreatePendingTenants::class,
Commands\ClearPendingTenants::class,

View file

@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace Stancl\Tenancy\TenantDatabaseManagers;
use Illuminate\Database\Connection;
use Illuminate\Support\Facades\DB;
use Stancl\Tenancy\Contracts\TenantDatabaseManager;
use Stancl\Tenancy\Contracts\TenantWithDatabase;
use Stancl\Tenancy\Exceptions\NoConnectionSetException;
class MicrosoftSQLDatabaseManager implements TenantDatabaseManager
{
/** @var string */
protected $connection;
protected function database(): Connection
{
if ($this->connection === null) {
throw new NoConnectionSetException(static::class);
}
return DB::connection($this->connection);
}
public function setConnection(string $connection): void
{
$this->connection = $connection;
}
public function createDatabase(TenantWithDatabase $tenant): bool
{
$database = $tenant->database()->getName();
$charset = $this->database()->getConfig('charset');
$collation = $this->database()->getConfig('collation');
return $this->database()->statement("CREATE DATABASE [{$database}]");
}
public function deleteDatabase(TenantWithDatabase $tenant): bool
{
return $this->database()->statement("DROP DATABASE [{$tenant->database()->getName()}]");
}
public function databaseExists(string $name): bool
{
return (bool) $this->database()->select("SELECT name FROM master.sys.databases WHERE name = '$name'");
}
public function makeConnectionConfig(array $baseConfig, string $databaseName): array
{
$baseConfig['database'] = $databaseName;
return $baseConfig;
}
}

View file

@ -5,26 +5,26 @@ declare(strict_types=1);
namespace Stancl\Tenancy\Tests;
use Illuminate\Filesystem\FilesystemAdapter;
use ReflectionObject;
use ReflectionProperty;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;
use Stancl\JobPipeline\JobPipeline;
use Stancl\Tenancy\Tests\Etc\Tenant;
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\Events\TenancyEnded;
use Stancl\Tenancy\Jobs\CreateDatabase;
use Stancl\Tenancy\Events\TenantCreated;
use Stancl\Tenancy\Events\TenancyInitialized;
use Stancl\Tenancy\Listeners\BootstrapTenancy;
use Stancl\Tenancy\Listeners\RevertToCentralContext;
use Illuminate\Support\Str;
use ReflectionObject;
use ReflectionProperty;
use Stancl\JobPipeline\JobPipeline;
use Stancl\Tenancy\Bootstrappers\CacheTenancyBootstrapper;
use Stancl\Tenancy\Bootstrappers\RedisTenancyBootstrapper;
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
use Stancl\Tenancy\Bootstrappers\FilesystemTenancyBootstrapper;
use Stancl\Tenancy\Bootstrappers\RedisTenancyBootstrapper;
use Stancl\Tenancy\Events\TenancyEnded;
use Stancl\Tenancy\Events\TenancyInitialized;
use Stancl\Tenancy\Events\TenantCreated;
use Stancl\Tenancy\Jobs\CreateDatabase;
use Stancl\Tenancy\Listeners\BootstrapTenancy;
use Stancl\Tenancy\Listeners\RevertToCentralContext;
use Stancl\Tenancy\Tests\Etc\Tenant;
class BootstrapperTest extends TestCase
{

View file

@ -91,6 +91,38 @@ class CommandsTest extends TestCase
$this->assertTrue(Schema::hasTable('users'));
}
/** @test */
public function migrate_command_loads_schema_state()
{
$tenant = Tenant::create();
$this->assertFalse(Schema::hasTable('schema_users'));
$this->assertFalse(Schema::hasTable('users'));
Artisan::call('tenants:migrate --schema-path="tests/Etc/tenant-schema.dump"');
$this->assertFalse(Schema::hasTable('schema_users'));
$this->assertFalse(Schema::hasTable('users'));
tenancy()->initialize($tenant);
// Check for both tables to see if missing migrations also get executed
$this->assertTrue(Schema::hasTable('schema_users'));
$this->assertTrue(Schema::hasTable('users'));
}
/** @test */
public function dump_command_works()
{
$tenant = Tenant::create();
Artisan::call('tenants:migrate');
tenancy()->initialize($tenant);
Artisan::call('tenants:dump --path="tests/Etc/tenant-schema-test.dump"');
$this->assertFileExists('tests/Etc/tenant-schema-test.dump');
}
/** @test */
public function rollback_command_works()
{

View file

@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace Stancl\Tenancy\Tests;
use Stancl\Tenancy\Database\Concerns\HasDomains;
use Stancl\Tenancy\Jobs\DeleteDomains;
class DeleteDomainsJobTest extends TestCase
{
public function setUp(): void
{
parent::setUp();
config(['tenancy.tenant_model' => DatabaseAndDomainTenant::class]);
}
/** @test */
public function job_delete_domains_successfully()
{
$tenant = DatabaseAndDomainTenant::create();
$tenant->domains()->create([
'domain' => 'foo.localhost',
]);
$tenant->domains()->create([
'domain' => 'bar.localhost',
]);
$this->assertSame($tenant->domains()->count(), 2);
(new DeleteDomains($tenant))->handle();
$this->assertSame($tenant->refresh()->domains()->count(), 0);
}
}
class DatabaseAndDomainTenant extends Etc\Tenant
{
use HasDomains;
}

View file

@ -19,7 +19,7 @@ class ExampleSeeder extends Seeder
{
DB::table('users')->insert([
'name' => Str::random(10),
'email' => Str::random(10).'@gmail.com',
'email' => Str::random(10) . '@gmail.com',
'password' => bcrypt('password'),
]);
}

View file

@ -0,0 +1,66 @@
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
DROP TABLE IF EXISTS `failed_jobs`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `failed_jobs` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`uuid` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`connection` text COLLATE utf8mb4_unicode_ci NOT NULL,
`queue` text COLLATE utf8mb4_unicode_ci NOT NULL,
`payload` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
`exception` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
`failed_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `failed_jobs_uuid_unique` (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `migrations`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `migrations` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`migration` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`batch` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `password_resets`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `password_resets` (
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
KEY `password_resets_email_index` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
DROP TABLE IF EXISTS `users`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `schema_users` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email_verified_at` timestamp NULL DEFAULT NULL,
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `users_email_unique` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
INSERT INTO `migrations` VALUES (2,'2014_10_12_100000_testbench_create_password_resets_table',1);
INSERT INTO `migrations` VALUES (3,'2019_08_19_000000_testbench_create_failed_jobs_table',1);

View file

@ -20,7 +20,6 @@ use Stancl\Tenancy\Jobs\CreateDatabase;
use Stancl\Tenancy\Jobs\MigrateDatabase;
use Stancl\Tenancy\Listeners\BootstrapTenancy;
use Stancl\Tenancy\Listeners\QueueableListener;
use Stancl\Tenancy\Tenancy;
use Stancl\Tenancy\Tests\Etc\Tenant;
class EventListenerTest extends TestCase

View file

@ -4,14 +4,12 @@ declare(strict_types=1);
namespace Stancl\Tenancy\Tests;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Http\Exceptions\MaintenanceModeException;
use Illuminate\Support\Facades\Route;
use Stancl\Tenancy\Database\Concerns\MaintenanceMode;
use Stancl\Tenancy\Middleware\CheckTenantForMaintenanceMode;
use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
use Stancl\Tenancy\Tests\Etc\Tenant;
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;
class MaintenanceModeTest extends TestCase
{

View file

@ -4,33 +4,31 @@ declare(strict_types=1);
namespace Stancl\Tenancy\Tests;
use Closure;
use Exception;
use Illuminate\Support\Str;
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\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\Events\JobProcessed;
use Illuminate\Queue\Events\JobProcessing;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use PDO;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Spatie\Valuestore\Valuestore;
use Stancl\JobPipeline\JobPipeline;
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
use Stancl\Tenancy\Bootstrappers\QueueTenancyBootstrapper;
use Stancl\Tenancy\Events\TenancyEnded;
use Stancl\Tenancy\Events\TenancyInitialized;
use Stancl\Tenancy\Events\TenantCreated;
use Stancl\Tenancy\Jobs\CreateDatabase;
use Stancl\Tenancy\Listeners\BootstrapTenancy;
use Stancl\Tenancy\Listeners\RevertToCentralContext;
use Stancl\Tenancy\Bootstrappers\QueueTenancyBootstrapper;
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
use Stancl\Tenancy\Tests\Etc\Tenant;
use Stancl\Tenancy\Tests\Etc\User;
class QueueTest extends TestCase
{

View file

@ -589,7 +589,9 @@ class CentralUser extends Model implements SyncMaster
use ResourceSyncing, CentralConnection;
protected $guarded = [];
public $timestamps = false;
public $table = 'users';
public function tenants(): BelongsToMany
@ -633,7 +635,9 @@ class ResourceUser extends Model implements Syncable
use ResourceSyncing;
protected $table = 'users';
protected $guarded = [];
public $timestamps = false;
public function getGlobalIdentifierKey()

View file

@ -329,6 +329,7 @@ class Post extends Model
use BelongsToTenant;
protected $guarded = [];
public $timestamps = false;
public function comments()
@ -345,6 +346,7 @@ class Post extends Model
class Comment extends Model
{
protected $guarded = [];
public $timestamps = false;
public function post()
@ -368,5 +370,6 @@ class ScopedComment extends Comment
class GlobalResource extends Model
{
protected $guarded = [];
public $timestamps = false;
}

View file

@ -19,6 +19,7 @@ use Stancl\Tenancy\Exceptions\TenantDatabaseAlreadyExistsException;
use Stancl\Tenancy\Jobs\CreateDatabase;
use Stancl\Tenancy\Listeners\BootstrapTenancy;
use Stancl\Tenancy\Listeners\RevertToCentralContext;
use Stancl\Tenancy\TenantDatabaseManagers\MicrosoftSQLDatabaseManager;
use Stancl\Tenancy\TenantDatabaseManagers\MySQLDatabaseManager;
use Stancl\Tenancy\TenantDatabaseManagers\PermissionControlledMySQLDatabaseManager;
use Stancl\Tenancy\TenantDatabaseManagers\PostgreSQLDatabaseManager;
@ -103,6 +104,7 @@ class TenantDatabaseManagerTest extends TestCase
['sqlite', SQLiteDatabaseManager::class],
['pgsql', PostgreSQLDatabaseManager::class],
['pgsql', PostgreSQLSchemaManager::class],
['sqlsrv', MicrosoftSQLDatabaseManager::class],
];
}
@ -194,7 +196,7 @@ class TenantDatabaseManagerTest extends TestCase
]);
tenancy()->initialize($tenant);
$schemaConfig = version_compare(app()->version(), '9.0', '>=') ?
$schemaConfig = version_compare(app()->version(), '9.0', '>=') ?
config('database.connections.' . config('database.default') . '.search_path') :
config('database.connections.' . config('database.default') . '.schema');

View file

@ -172,6 +172,7 @@ class MyTenant extends Tenant
class AnotherTenant extends Model implements Contracts\Tenant
{
protected $guarded = [];
protected $table = 'tenants';
public function getTenantKeyName(): string

View file

@ -274,11 +274,13 @@ class TenantUserImpersonationTest extends TestCase
class ImpersonationUser extends Authenticable
{
protected $guarded = [];
protected $table = 'users';
}
class AnotherImpersonationUser extends Authenticable
{
protected $guarded = [];
protected $table = 'users';
}

View file

@ -81,6 +81,10 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase
],
'database.connections.sqlite.database' => ':memory:',
'database.connections.mysql.host' => env('TENANCY_TEST_MYSQL_HOST', '127.0.0.1'),
'database.connections.sqlsrv.username' => env('TENANCY_TEST_SQLSRV_USERNAME', 'sa'),
'database.connections.sqlsrv.password' => env('TENANCY_TEST_SQLSRV_PASSWORD', 'P@ssword'),
'database.connections.sqlsrv.host' => env('TENANCY_TEST_SQLSRV_HOST', '127.0.0.1'),
'database.connections.sqlsrv.database' => null,
'database.connections.pgsql.host' => env('TENANCY_TEST_PGSQL_HOST', '127.0.0.1'),
'tenancy.filesystem.disks' => [
'local',