UserPermissionHelper.php 2.27 KB
<?php

namespace App\Helpers;

use App\Models\SystemTag;
use App\Models\User;
use App\Models\UserTagRelation;
use Arr;

class UserPermissionHelper
{
    public User $user;

    /**
     * @param \App\Models\User $user
     */
    private function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * @param int|\App\Models\User $user
     * @return \App\Helpers\UserPermissionHelper
     */
    public static function user(int|User $user): UserPermissionHelper
    {
        return new self(is_numeric($user) ? User::findOrFail($user, ['id', 'identity', 'demo_type', 'scope']) : $user);
    }

    /**
     * @param int|array $tagIds
     * @return bool
     */
    public function checkTag(int|array $tagIds): bool
    {
        return UserTagRelation::query()->where('type', 4)->where('user_id', $this->user->getKey())->whereIn('tag_id', Arr::wrap($tagIds))->exists();
    }

    /**
     * @return bool
     */
    public function hasDemoPermission(): bool
    {
        if ($this->user->getAttribute('demo_type') === 0) {
            return false;
        }

        $config = ConfigHelper::getDemoList();

        if (in_array($this->user->getKey(), $config->get(ConfigHelper::DEMO_USER_KEY), false)) {
            return true;
        }

        return $this->checkTag($config->get(ConfigHelper::DEMO_TAG_KEY));
    }

    /**
     * @return bool
     */
    public function hasSingPermission(): bool
    {
        if (in_array($this->user->getKey(), ConfigHelper::getSingUserIds(), false)) {
            return true;
        }

        return $this->checkTag(SystemTag::query()->whereJsonContains('expand->permission', [2])->pluck('id')->merge(ConfigHelper::getSingerTagIds())->toArray());
    }

    /**
     * @return bool
     */
    public function hasListenPermission(): bool
    {
        if ($this->hasSingPermission() || in_array($this->user->getAttribute('identity'), [2, 3], false) || in_array($this->user->getKey(), ConfigHelper::getListenUserIds(), false)) {
            return true;
        }

        return $this->checkTag(SystemTag::query()->whereJsonContains('expand->permission', [1])->pluck('id')->toArray());
    }


    /**
     * @return bool
     */
    public function isSinger(): bool
    {
        return $this->checkTag(ConfigHelper::getSingerTagIds());
    }
}