presseportale/app/Models/Company.php
Kevin Adametz dba76910ca Optimierung 3.1: Company::scopeAccessibleBy() zentralisiert Firmenzugriff
Die 4x identische Zugriffs-Closure (owner_user_id == me OR whereHas('users',
me)) in CompanyController (index/show), PressReleaseController::
findOwnedCompany und CustomerCompanyContext::accessibleCompanyQuery durch
einen Company::scopeAccessibleBy() ersetzt; das Scope-Verhalten
(withoutGlobalScopes) bleibt beim Aufrufer.

Bewusst unangetastet: User::accessibleCompanyIds() (relationenbasiert MIT
globalen Scopes - anderes Scope-Verhalten) und PressReleaseImageController
(prueft PR-Autorschaft user_id, nicht Firmenzugriff).

Tests: neuer Scope-Test; volle Suite gruen (801 passed, 1 skipped).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 10:23:16 +00:00

183 lines
5.3 KiB
PHP

<?php
namespace App\Models;
use App\Enums\CompanyType;
use App\Enums\Portal;
use App\Models\Concerns\HasUniqueSlug;
use App\Scopes\PortalScope;
use Database\Factories\CompanyFactory;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class Company extends Model
{
/** @use HasFactory<CompanyFactory> */
use HasFactory, HasUniqueSlug, SoftDeletes;
/**
* @return list<string>
*/
protected function slugScopeAttributes(): array
{
return ['portal'];
}
protected function slugFallback(): string
{
return 'company';
}
protected static function booted(): void
{
static::addGlobalScope(new PortalScope);
}
protected $fillable = [
'portal',
'owner_user_id',
'type',
'name',
'slug',
'address',
'country_code',
'phone',
'fax',
'email',
'website',
'logo_path',
'logo_variants',
'boilerplate',
'is_active',
'disable_footer_code',
'legacy_portal',
'legacy_id',
];
protected function casts(): array
{
return [
'portal' => Portal::class,
'type' => CompanyType::class,
'logo_variants' => 'array',
'is_active' => 'boolean',
'disable_footer_code' => 'boolean',
'deleted_at' => 'datetime',
];
}
/**
* Firmensuche für die Admin-Combobox: Volltext (name/email/slug) bei
* unterstützenden Treibern und Suchbegriffen ab 3 Zeichen, sonst LIKE.
* Bei leerem Begriff bleibt die Query unverändert. Single Source of Truth
* für die zuvor in mehreren Editoren duplizierte Such- und Treiberlogik.
*/
public function scopeSearchByTerm(Builder $query, string $term): Builder
{
$term = Portal::stripTrailingAbbreviation($term);
if (! filled($term)) {
return $query;
}
$supportsFullText = mb_strlen($term) >= 3
&& in_array(DB::connection()->getDriverName(), ['mysql', 'pgsql'], true);
return $query->where(function (Builder $query) use ($term, $supportsFullText): void {
if ($supportsFullText) {
$query->whereFullText(['name', 'email', 'slug'], $term);
return;
}
$query->where('name', 'like', '%'.$term.'%')
->orWhere('slug', 'like', '%'.$term.'%');
});
}
/**
* Firmen, auf die ein User zugreifen darf: als Owner (owner_user_id) oder
* als Mitglied über den company_user-Pivot. Single Source of Truth für die
* zuvor in mehreren API-Controllern und Services duplizierte Closure. Das
* Scope-Verhalten (mit/ohne globale Scopes) bestimmt der Aufrufer.
*/
public function scopeAccessibleBy(Builder $query, User $user): Builder
{
return $query->where(function (Builder $query) use ($user): void {
$query->where('owner_user_id', $user->id)
->orWhereHas('users', fn (Builder $users) => $users->whereKey($user->id));
});
}
public function owner(): BelongsTo
{
return $this->belongsTo(User::class, 'owner_user_id');
}
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class)
->withPivot('role')
->withTimestamps();
}
public function contacts(): HasMany
{
return $this->hasMany(Contact::class);
}
public function pressReleases(): HasMany
{
return $this->hasMany(PressRelease::class);
}
public function userPaymentOptions(): BelongsToMany
{
return $this->belongsToMany(UserPaymentOption::class, 'user_payment_option_company')
->withPivot('is_active')
->withTimestamps();
}
public function logoUrl(): ?string
{
if (blank($this->logo_path)) {
return null;
}
$logoPath = trim((string) $this->logo_path);
$legacyPortal = $this->legacy_portal ?: $this->portal?->value;
$logoFilename = basename((string) (parse_url($logoPath, PHP_URL_PATH) ?: $logoPath));
$candidates = [];
if (Str::startsWith($logoPath, '/storage/')) {
$candidates[] = Str::after($logoPath, '/storage/');
} elseif (! Str::startsWith($logoPath, ['http://', 'https://'])) {
$candidates[] = ltrim($logoPath, '/');
}
if ($legacyPortal && filled($logoFilename)) {
$candidates[] = "company-logos/{$legacyPortal}/{$this->id}/{$logoFilename}";
$candidates[] = "{$legacyPortal}/company/{$logoFilename}";
}
foreach (array_unique($candidates) as $candidate) {
if (Storage::disk('public')->exists($candidate)) {
return asset('storage/'.$candidate);
}
}
if (Str::startsWith($logoPath, ['http://', 'https://']) && blank($this->legacy_portal)) {
return $logoPath;
}
return null;
}
}