spotonlive / sl-assertions by nikolajlovenhardt

Assertions for Laravel 5.1
1,693
2
3
Package Data
Maintainer Username: nikolajlovenhardt
Maintainer Contact: nikolaj.lovenhardt@gmail.com (Nikolaj Petersen)
Package Create Date: 2015-09-10
Package Last Update: 2018-09-20
Language: PHP
License: MIT
Last Refreshed: 2024-04-17 15:16:58
Package Statistics
Total Downloads: 1,693
Monthly Downloads: 0
Daily Downloads: 0
Total Stars: 2
Total Watchers: 3
Total Forks: 0
Total Open Issues: 0

Assertions for Laravel 5.1

Latest Stable Version Total Downloads Latest Unstable Version License Code Climate Test Coverage

THIS PACKAGE IS UNDER DEVELOPMENT

Configuration

Installation

Run $ composer require spotonlive/sl-assertions

config/app.php Insert the provider and helper alias into your application configuration

    'providers' => [
        \SpotOnLive\Assertions\Providers\Services\AssertionServiceProvider::class,
        \SpotOnLive\Assertions\Providers\Helpers\AssertionHelperProvider::class,
    ]

    'aliases' => [
        'AssertionHelper' => \SpotOnLive\Assertions\Facades\Helpers\AssertionHelperFacade::class,
    ]

Configuration

run $ php artisan vendor:publish to create the configuration file. A configuration file is now available in config/assertions.php.

Assertions

To create new examples create a new assertion file implementing the assertion interface. For example:

EditAssertion.php

<?php

namespace App\Assertions\Users;

use SpotOnLive\Assertions\AssertionInterface;
use App\Entities\User;

class EditAssertion implements AssertionInterface
{
    /**
     * @param User $user
     * @param array $data
     * @return bool
     */
    public function assert($user, array $data = [])
    {
        /** @var User $userToEdit */
        $userToEdit = $data['user'];

        return $user == $userToEdit || $user->hasRole(['superadmin', 'admin']);
    }
}

And then register the assertion in your configuration file:

config/assertions.php

<?php

return [
    'users.edit' => \App\Assertions\Users\EditAssertion::class,
];

Usage

Service

Use the assertion service by injecting AssertionService.

app::make('AssertionService')

Example:

<?php

namespace App\Controllers;

use \SpotOnLive\Assertions\Services\AssertionServiceInterface;

class Controller
{
    /** @var AssertionServiceInterface **/
    protected $assertionService;

    public function __construct(AssertionServiceInterface $assertionService)
    {
        $this->assertionService = $assertionService;
    }

    public function admin()
    {
        if (!$this->assertionService->isGranted('admin.page', Auth::user())) {
            return redirect()->route('not-granted');
        }

        return view('admin.page');
    }
}

Helper

Use the AssertionHelper directly in your views.

Example: view.blade.php

@if(AssertionHelper::isGranted('user.edit', Auth::user(), ['user' => $user]))
    <a href="{{URL::route('user.edit')}}">{{_('Edit user')}}</a>
@endif

Organization & authors