1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2026-02-05 20:14:04 +00:00
tenancy/src/Database/Concerns/DealsWithModels.php
2023-06-19 15:24:39 +02:00

64 lines
2.1 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
declare(strict_types=1);
namespace Stancl\Tenancy\Database\Concerns;
use Closure;
use Illuminate\Database\Eloquent\Model;
use ReflectionClass;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
trait DealsWithModels
{
/**
* If this is not null, use this instead of the default model discovery logic.
*/
public static Closure|null $modelDiscoveryOverride = null;
/**
* Discover all models in the directories configured in 'tenancy.rls.model_directories'.
*/
public static function getModels(): array
{
if (static::$modelDiscoveryOverride) {
return (static::$modelDiscoveryOverride)();
}
$modelFiles = Finder::create()->files()->name('*.php')->in(config('tenancy.rls.model_directories'));
return array_filter(array_map(function (SplFileInfo $file) {
$fileContents = str($file->getContents());
$class = $fileContents->after('class ')->before("\n")->explode(' ')->first();
if ($fileContents->contains('namespace ')) {
try {
return new ($fileContents->after('namespace ')->before(';')->toString() . '\\' . $class);
} catch (\Throwable $th) {
// Skip non-instantiable classes we only care about models, and those are instantiable
}
}
return null;
}, iterator_to_array($modelFiles)));
}
/**
* Filter all models retrieved by static::getModels() to get only the models that belong to tenants.
*/
public static function getTenantModels(): array
{
return array_filter(static::getModels(), fn (Model $model) => tenancy()->modelBelongsToTenant($model) || tenancy()->modelBelongsToTenantIndirectly($model));
}
public static function modelBelongsToTenant(Model $model): bool
{
return in_array(BelongsToTenant::class, class_uses_recursive($model::class));
}
public static function modelBelongsToTenantIndirectly(Model $model): bool
{
return in_array(BelongsToPrimaryModel::class, class_uses_recursive($model::class));
}
}