HEX
Server: LiteSpeed
System: Linux s1049.use1.mysecurecloudhost.com 4.18.0-477.27.2.lve.el8.x86_64 #1 SMP Wed Oct 11 12:32:56 UTC 2023 x86_64
User: xedaptot (3356)
PHP: 8.3.31
Disabled: NONE
Upload Files
File: /home/xedaptot/be.naniguide.com/app/Policies/NotificationPolicy.php
<?php

namespace App\Policies;

use App\Model\Admin;
use App\Model\AppNotification;
use App\Model\Customer;
use App\Model\User;
use App\Notifications\AppNotification as Event;

/**
 * Authorizes who can act (mark read/unread/dismiss) on a notification row.
 *
 *   - direct: only the named recipient (Admin or Customer matching
 *     notifiable_type/id) may act
 *   - admins: any admin may act (first-come-first-handle; row is shared)
 *   - customers: any customer may act
 *   - everyone: any authenticated user may act
 *
 * The default switch enforces the no-fall-through rule (project HARD RULE):
 * unknown audiences throw rather than silently allowing or denying.
 */
class NotificationPolicy
{
    public function act(User $user, AppNotification $notification): bool
    {
        return match ($notification->audience) {
            Event::AUDIENCE_DIRECT    => $this->isNamedRecipient($user, $notification),
            Event::AUDIENCE_ADMINS    => $user->admin !== null,
            Event::AUDIENCE_CUSTOMERS => $user->customer !== null,
            Event::AUDIENCE_EVERYONE  => true,
            default                   => throw new \LogicException(
                "Unhandled notification audience in NotificationPolicy::act: {$notification->audience}"
            ),
        };
    }

    private function isNamedRecipient(User $user, AppNotification $n): bool
    {
        return match ($n->notifiable_type) {
            (new Admin)->getMorphClass()    => $user->admin && $user->admin->id === (int) $n->notifiable_id,
            (new Customer)->getMorphClass() => $user->customer && $user->customer->id === (int) $n->notifiable_id,
            default                         => false,
        };
    }
}