PHP code example of agroezinger / filament-shield-enhanced

1. Go to this page and download the library: Download agroezinger/filament-shield-enhanced library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

agroezinger / filament-shield-enhanced example snippets




namespace App\Filament\Pages;

use Agroezinger\FilamentShieldEnhanced\Traits\HasPageShield;
use Filament\Pages\Page;

class SettingsPage extends Page
{
    use HasPageShield;

    /**
     * Declare every action that can be independently granted on this page.
     * The 'view' action controls whether the user can navigate to the page at all.
     *
     * Three entry formats can be mixed freely:
     *
     *   'action'                          → label auto-generated from action name
     *   'action' => 'Label'               → explicit label
     *   'action' => ['text'        => 'Label',
     *                'description' => 'Shown below the checkbox in the role editor']
     */
    public static function getShieldPagePermissions(): array
    {
        return [
            'view'               => 'Can view this page',
            'editGlobalSettings' => [
                'text'        => 'Can change global settings',
                'description' => 'Grants access to all fields in the Global Settings section.',
            ],
            'exportData'         => 'Can export data as CSV / Excel',
        ];
    }
}

// Inside the Page class
if ($this->canShield('editGlobalSettings')) {
    // Perform restricted action
}



namespace App\Livewire;

use Agroezinger\FilamentShieldEnhanced\Traits\HasInjectedShieldPermissions;
use Livewire\Component;

class SettingsSidebar extends Component
{
    use HasInjectedShieldPermissions;

    // $this->permissions is automatically populated by Livewire.

    public function save(): void
    {
        $this->authorizeShield('editGlobalSettings'); // aborts 403 if not permitted
        // … save logic
    }

    public function render()
    {
        return view('livewire.settings-sidebar');
    }
}



namespace App\Filament\Resources;

use Agroezinger\FilamentShieldEnhanced\Traits\HasResourceShield;
use App\Models\Member;
use Filament\Resources\Resource;

class MemberResource extends Resource
{
    use HasResourceShield;

    protected static ?string $model = Member::class;

    /**
     * Declare custom permissions beyond the standard CRUD policy methods.
     * Keys are action names; values are human-readable labels (shown in the role editor).
     *
     * Same three entry formats as getShieldPagePermissions():
     *   'action'                                   → auto-generated label
     *   'action' => 'Label'                        → explicit label
     *   'action' => ['text' => '...', 'description' => '...']
     */
    public static function getShieldResourcePermissions(): array
    {
        return [
            'Export'          => 'Export member list (basic data)',
            'ExportFinance'   => 'Export member list including financial data (IBAN, fees)',
            'ViewContactInfo' => 'View contact details (email, phone, address)',
            'ViewBankingInfo' => 'View bank details (IBAN, BIC, account holder)',
        ];
    }
}

// Anywhere in your application
if (MemberResource::canShield('ViewContactInfo')) {
    // show contact section
}

// Returns ['Export' => true, 'ViewContactInfo' => false, …]
$permissions = MemberResource::getShieldPermissions();

class SquadResource extends Resource
{
    // No HasResourceShield/getShieldResourcePermissions() needed — this hook
    // works standalone against filament-shield's own standard CRUD keys too.

    public static function getShieldPermissionDescriptions(): array
    {
        $hint = 'Applies to ALL squads — team-manager assignment and department '
            . 'scoping are not enforced here yet.';

        return [
            'View:Squad'   => $hint,
            'Update:Squad' => $hint,
            'Delete:Squad' => $hint,
        ];
    }
}



namespace App\Livewire;

use Agroezinger\FilamentShieldEnhanced\Traits\HasComponentShield;
use Livewire\Component;

class CommentComponent extends Component
{
    use HasComponentShield;

    /**
     * No default action — unlike pages there is no universally meaningful
     * "view" action for an arbitrary component, so declare exactly what you need.
     * Same three entry formats as getShieldPagePermissions().
     */
    public static function getShieldComponentPermissions(): array
    {
        return [
            'delete' => 'Can delete any comment',
            'edit'   => 'Can edit any comment',
        ];
    }

    public function delete(int $commentId): void
    {
        $this->authorizeShield('delete'); // aborts 403 if not permitted
        // …
    }
}

// Inside the component class
if ($this->canShield('delete')) {
    // Show the delete button
}

use Agroezinger\FilamentShieldEnhanced\Forms\EnhancedComponentPermissionsForm;
use Agroezinger\FilamentShieldEnhanced\Forms\EnhancedPagePermissionsForm;
use Agroezinger\FilamentShieldEnhanced\Forms\EnhancedResourcePermissionsForm;
use Filament\Schemas\Components\Tabs;
use Filament\Schemas\Components\Tabs\Tab;

public static function getShieldFormComponents(): \Filament\Schemas\Components\Component
{
    $resourceComponents = EnhancedResourcePermissionsForm::make();
    $resourceCount      = array_sum(array_map('count', EnhancedResourcePermissionsForm::getResourcePermissionFields()));

    $pageComponents = EnhancedPagePermissionsForm::make();
    $pageCount      = array_sum(array_map('count', EnhancedPagePermissionsForm::getPagePermissionFields()));

    $componentComponents = EnhancedComponentPermissionsForm::make();
    $componentCount      = array_sum(array_map('count', EnhancedComponentPermissionsForm::getComponentPermissionFields()));

    $tabs = [
        static::getTabFormComponentForWidget(),
        static::getTabFormComponentForCustomPermissions(),
    ];

    if (! empty($resourceComponents)) {
        $tabs[] = Tab::make('resources')
            ->label('Resources')
            ->badge($resourceCount ?: null)
            ->schema($resourceComponents);
    }

    if (! empty($pageComponents)) {
        $tabs[] = Tab::make('pages')
            ->label('Pages')
            ->badge($pageCount ?: null)
            ->schema($pageComponents);
    }

    if (! empty($componentComponents)) {
        $tabs[] = Tab::make('components')
            ->label('Components')
            ->badge($componentCount ?: null)
            ->schema($componentComponents);
    }

    return Tabs::make('Permissions')
        ->contained()
        ->tabs($tabs)
        ->columnSpan('full');
}

use Agroezinger\FilamentShieldEnhanced\Traits\HasEnhancedRoleForm;

class EditRole extends EditRecord
{
    use HasEnhancedRoleForm;

    // … rest of the file unchanged
}

use Agroezinger\FilamentShieldEnhanced\Forms\EnhancedPagePermissionsForm;
use Agroezinger\FilamentShieldEnhanced\Forms\EnhancedResourcePermissionsForm;
use Agroezinger\FilamentShieldEnhanced\Support\NavigationGroupResolver;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Tabs;
use Filament\Schemas\Components\Tabs\Tab;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;

public static function getShieldFormComponents(): \Filament\Schemas\Components\Component
{
    $entries = EnhancedResourcePermissionsForm::discoverResources()
        ->map(fn (array $entry): array => $entry + ['category' => 'resources'])
        ->concat(
            EnhancedPagePermissionsForm::discoverPages()
                ->map(fn (array $entry): array => $entry + ['category' => 'pages'])
        );

    $grouped    = $entries->groupBy('navigationGroup');
    $ungrouped  = $grouped->get('', collect()); // Resources/Pages with no $navigationGroup
    $groupOrder = NavigationGroupResolver::order();
    $groupSort  = config('filament-shield-enhanced.ui.group_sort', 'navigation');

    $tabs = $grouped->except([''])
        ->sortBy(fn (Collection $g, string $label) => $groupSort === 'alphabetical'
            ? $label
            : (array_search($label, $groupOrder, true) === false ? count($groupOrder) : array_search($label, $groupOrder, true)))
        ->map(fn (Collection $g, string $label) => Tab::make(Str::slug($label ?: 'misc'))
            ->label($label ?: config('filament-shield-enhanced.ui.labels.misc_group', 'Miscellaneous'))
            ->badge($g->count())
            ->schema(static::buildCategorySchema($g)))
        ->values()
        ->all();

    return Tabs::make('Permissions')->contained()->tabs($tabs)->columnSpan('full');
}

/**
 * Collects the Resources/Pages sub-tabs as plain data (label/badge/schema)
 * rather than building Tab objects straight away: a Tab can only be
 * introspected (e.g. to read its schema back out) once it's attached to a
 * container, which only happens when it's handed to a parent Tabs::make() —
 * so if only one category ends up present, this reaches for the raw
 * $categories entry directly instead of building-then-unwrapping a Tab.
 */
protected static function buildCategorySchema(Collection $entries): array
{
    $labels = [
        'resources' => config('filament-shield-enhanced.ui.labels.resources', 'Management Areas'),
        'pages'     => config('filament-shield-enhanced.ui.labels.pages', 'Function Pages'),
    ];

    $categories = collect($labels)
        ->map(function (string $label, string $category) use ($entries): ?array {
            $categoryEntries = $entries->where('category', $category);
            if ($categoryEntries->isEmpty()) return null;

            $sections = $categoryEntries->sortBy('navigationSort')->map(
                fn (array $entry) => $category === 'resources'
                    ? EnhancedResourcePermissionsForm::buildSection($entry)
                    : EnhancedPagePermissionsForm::buildSection($entry)
            )->all();

            return ['label' => $label, 'badge' => $categoryEntries->count(), 'schema' => [Grid::make()->schema($sections)]];
        })
        ->filter()
        ->values();

    if ($categories->count() > 1) {
        return [Tabs::make('categories')->tabs(
            $categories->map(fn (array $c, int $i) => Tab::make('cat_' . $i)->label($c['label'])->badge($c['badge'])->schema($c['schema']))->all()
        )];
    }

    return $categories->first()['schema'] ?? [];
}

// config/filament-shield-enhanced.php

return [
    'pages' => [
        // First segment of the three-part key: Page:Action:Subject
        'permission_prefix' => 'Page',
    ],

    'components' => [
        // First segment of the three-part key: Component:Action:Subject
        'permission_prefix' => 'Component',

        // Directories scanned for classes using HasComponentShield, each
        // mapped to its base namespace. Add more entries if components
        // live outside app/Livewire.
        'scan_paths' => [
            app_path('Livewire') => 'App\\Livewire',
        ],
    ],

    'ui' => [
        'grid_columns' => [
            'default' => 1,
            'sm'      => 2,
            'lg'      => 3,
        ],

        'checkbox_list_columns' => [
            'default' => 1,
            'sm'      => 2,
        ],

        // None of the three keys below are read by make() itself — make()
        // always groups by navigation order and always calls things
        // "Resources"/"Pages". They exist purely as a shared config contract
        // for apps implementing the §8c recipe; nothing happens unless your
        // own getShieldFormComponents() reads them (as the §8c snippet does).
        'group_by_navigation' => true,

        'group_sort' => 'navigation', // 'navigation' | 'alphabetical'

        // End users configuring roles don't know what a Filament "Resource"
        // or "Page" is — override with labels that describe what the
        // category lets someone DO. The defaults already avoid the raw
        // Filament terms; treat them as a starting point, not a fixed set.
        'labels' => [
            'resources'  => 'Management Areas',
            'pages'      => 'Function Pages',
            'widgets'    => 'Dashboard Widgets',
            'custom'     => 'Other Permissions',
            'misc_group' => 'Miscellaneous',
        ],
    ],
];

FilamentShield::buildPermissionKeyUsing(function (...) { ... });
bash
php artisan vendor:publish --tag="filament-shield-enhanced-config"
blade
@livewire('settings-sidebar', [
    'permissions' => $this->getShieldPermissions()
])
bash
php artisan shield:generate-enhanced-components