PHP Trait Efficiently\AuthorityController\ControllerAdditions

Show file Open project: efficiently/authority-controller

Protected Properties

Property Type Description
$_authorized
$afterFilters array The "after" filters registered on the controller.
$beforeFilters array The "before" filters registered on the controller.
$currentAuthority Sadly, we can't set an empty array as default value here, maybe a PHP Trait bug ?
$currentUser
$params

Public Methods

Method Description
afterFilter ( Closure | string $filter, array $options = [] ) : void Register an "after" filter on the controller.
authorize ( $args = null ) Throws a Efficiently\AuthorityController\Exceptions\AccessDenied exception if the currentAuthority cannot perform the given action. This is usually called in a controller action or before filter to perform the authorization.
authorizeResource ( $args = null ) Sets up a before filter which authorizes the resource using the instance variable.
beforeFilter ( Closure | string $filter, array $options = [] ) : void Register a "before" filter on the controller.
callAction ( string $method, array $parameters ) : Response Execute an action on the controller.
can ( $args = null ) Use in the controller or view to check the user's permission for a given action and object.
cannot ( $args = null ) Convenience method which works the same as "can()" but returns the opposite value.
flushAuthorityEvents ( $controllerName = null ) : void Remove all of the Authority-Controller event listeners of the specified controller.
forgetAfterFilter ( string $filter ) : void Remove the given after filter.
forgetBeforeFilter ( string $filter ) : void Remove the given before filter.
getAfterFilters ( ) : array Get the registered "after" filters.
getBeforeFilters ( ) : array Get the registered "before" filters.
getCurrentAbility ( ) alias of getCurrentAuthority() to match CanCan API
getCurrentAuthority ( ) Creates and returns the current user's authority and caches it. If you want to override how the Authority is defined then this is the place.
getCurrentUser ( )
getParams ( ) }
loadAndAuthorizeResource ( $args = null ) Sets up a before filter which loads and authorizes the current resource. This performs both loadResource() and authorizeResource() and accepts the same arguments. See those methods for details.
loadResource ( $args = null ) Sets up a before filter which loads the model resource into an instance variable.
paramsBeforeFilter ( $filter, array $options = [] )
prependAfterFilter ( string $filter, array $options = [] ) : void Register a new "after" filter before any "after" filters on the controller.
prependBeforeFilter ( string $filter, array $options = [] ) : void Register a new "before" filter before any "before" filters on the controller.
setCurrentAbility ( $ability ) alias of setCurrentAuthority() to match CanCan API
setCurrentAuthority ( $authority )

Protected Methods

Method Description
assignAfter ( Illuminate\Routing\Route $route, Illuminate\Http\Request $request, string $method ) : mixed Apply the applicable after filters to the route.
before ( Illuminate\Routing\Route $route, Illuminate\Http\Request $request, string $method ) : mixed Call the "before" filters for the controller.
callFilter ( array $filter, Illuminate\Routing\Route $route, Illuminate\Http\Request $request ) : mixed Call the given controller filter method.
callRouteFilter ( string $filter, array $parameters, Illuminate\Routing\Route $route, Illuminate\Http\Request $request, Illuminate\Http\Response | null $response = null ) : mixed Call the given route filter.
cleanFilterParameters ( array $parameters ) : array Clean the parameters being passed to a filter callback.
filterApplies ( array $filter, Illuminate\Http\Request $request, string $method ) : boolean Determine if the given filter applies to the request.
filterFailsMethod ( array $filter, Illuminate\Http\Request $request, string $method ) : boolean Determine if the filter fails the method constraints.
getAssignableAfter ( string $filter ) : string Get the assignable after filter for the route.
methodExcludedByOptions ( string $method, array $options ) : boolean Determine if the given options exclude a particular method.
parseFilter ( string $filter, array $options ) : array Parse the given filter and options.
removeFilter ( string $removing, array $current ) : array Remove the given controller filter from the provided filter array.

Method Details

afterFilter() public method

Register an "after" filter on the controller.
public afterFilter ( Closure | string $filter, array $options = [] ) : void
$filter Closure | string
$options array
return void

assignAfter() protected method

Apply the applicable after filters to the route.
protected assignAfter ( Illuminate\Routing\Route $route, Illuminate\Http\Request $request, string $method ) : mixed
$route Illuminate\Routing\Route
$request Illuminate\Http\Request
$method string
return mixed

authorize() public method

public function show($id) { $this->article = Article::find($id); // Tips: instead of $id, you can use $this->params['id'] $this->authorize('read', $this->article); But you still need to return the view return view('articles.show', compact_property($this, 'article')); } A 'message' option can be passed to specify a different message. $this->authorize('read', $this->article, ['message' => "Not authorized to read ".$this->article->name]); You can also use I18n to customize the message. Action aliases defined in Authority work here. return [ 'unauthorized' => [ 'manage' => [ 'all' => "Not authorized to :action :subject.", 'user' => "Not allowed to manage other user accounts.", ], 'update' => [ 'project' => "Not allowed to update this project." ], ], ]; You can catch the exception and modify its behavior in the report() method of the app/Exceptions/Handler.php file. For example here we set the error message to a flash and redirect to the home page. public function report(Exception $e) { if ($e instanceof \Efficiently\AuthorityController\Exceptions\AccessDenied) { $msg = $e->getMessage(); \Log::error('Access denied! '.$msg); return redirect()->route('home')->with('flash_alert', $msg); } return parent::report($e); } code... See the Efficiently\AuthorityController\Exceptions\AccessDenied exception for more details on working with the exception. See the loadAndAuthorizeResource() method to automatically add the authorize() behavior to the default RESTful actions.
public authorize ( $args = null )

authorizeResource() public method

For example, if you have an ArticlesController it will check the $this->article instance variable and ensure the user can perform the current action on it. Under the hood it is doing something like the following. $this->authorize($this->params['action'], $this->article ?: 'Article') Call this method directly on the controller class. class BooksController extends Controller { public function __construct() { $this->authorizeResource(); } } If you pass in the name of a resource which does not match the controller it will assume it is a parent resource. class BooksController extends Controller { public function __construct() { $this->authorizeResource('author'); $this->authorizeResource('book'); } } Here it will authorize 'show', $this->author on every action before authorizing the book. That first argument is optional and will default to the singular name of the controller. A hash of options (see below) can also be passed to this method to further customize it. See loadAndAuthorizeResource() to automatically load the resource too. Options: ['only'] Only applies before filter to given actions. ['except'] Does not apply before filter to given actions. ['singleton'] Pass true if this is a singleton resource through a hasOne association. ['parent'] True or false depending on if the resource is considered a parent resource. This defaults to true if a resource name is given which does not match the controller. ['class'] The class to use for the model (string). This passed in when the instance variable is not set. Pass false if there is no associated class for this resource and it will use a symbol of the resource name. ['instance_name'] The name of the instance variable for this resource. ['through'] Authorize conditions on this parent resource when instance isn't available. ['prepend'] Passing true will use prependBeforeFilter() instead of a normal beforeFilter().
public authorizeResource ( $args = null )

before() protected method

Call the "before" filters for the controller.
protected before ( Illuminate\Routing\Route $route, Illuminate\Http\Request $request, string $method ) : mixed
$route Illuminate\Routing\Route
$request Illuminate\Http\Request
$method string
return mixed

beforeFilter() public method

Register a "before" filter on the controller.
public beforeFilter ( Closure | string $filter, array $options = [] ) : void
$filter Closure | string
$options array
return void

callAction() public method

Execute an action on the controller.
public callAction ( string $method, array $parameters ) : Response
$method string
$parameters array
return Symfony\Component\HttpFoundation\Response

callFilter() protected method

Call the given controller filter method.
protected callFilter ( array $filter, Illuminate\Routing\Route $route, Illuminate\Http\Request $request ) : mixed
$filter array
$route Illuminate\Routing\Route
$request Illuminate\Http\Request
return mixed

callRouteFilter() protected method

Call the given route filter.
protected callRouteFilter ( string $filter, array $parameters, Illuminate\Routing\Route $route, Illuminate\Http\Request $request, Illuminate\Http\Response | null $response = null ) : mixed
$filter string
$parameters array
$route Illuminate\Routing\Route
$request Illuminate\Http\Request
$response Illuminate\Http\Response | null
return mixed

can() public method

$this->can('destroy', $this->project); You can also pass the class instead of an instance (if you don't have one handy).
public can ( $args = null )

cannot() public method

$this->cannot('destroy', $this->project);
public cannot ( $args = null )

cleanFilterParameters() protected method

Clean the parameters being passed to a filter callback.
protected cleanFilterParameters ( array $parameters ) : array
$parameters array
return array

filterApplies() protected method

Determine if the given filter applies to the request.
protected filterApplies ( array $filter, Illuminate\Http\Request $request, string $method ) : boolean
$filter array
$request Illuminate\Http\Request
$method string
return boolean

filterFailsMethod() protected method

Determine if the filter fails the method constraints.
protected filterFailsMethod ( array $filter, Illuminate\Http\Request $request, string $method ) : boolean
$filter array
$request Illuminate\Http\Request
$method string
return boolean

flushAuthorityEvents() public static method

If $controllerName == '*', it removes all the Authority-Controller events of every Controllers of the application. \App\Http\Controllers\Controller::flushAuthorityEvents('*'); // Remove all Authority-Controller events of every Controllers \App\Http\Controllers\ProjectsController::flushAuthorityEvents(); // Remove all Authority-Controller events of ProjectsController
public static flushAuthorityEvents ( $controllerName = null ) : void
return void

forgetAfterFilter() public method

Remove the given after filter.
public forgetAfterFilter ( string $filter ) : void
$filter string
return void

forgetBeforeFilter() public method

Remove the given before filter.
public forgetBeforeFilter ( string $filter ) : void
$filter string
return void

getAfterFilters() public method

Get the registered "after" filters.
public getAfterFilters ( ) : array
return array

getAssignableAfter() protected method

Get the assignable after filter for the route.
protected getAssignableAfter ( string $filter ) : string
$filter string
return string

getBeforeFilters() public method

Get the registered "before" filters.
public getBeforeFilters ( ) : array
return array

getCurrentAbility() public method

alias of getCurrentAuthority() to match CanCan API
public getCurrentAbility ( )

getCurrentAuthority() public method

Just define the method in the controller to change behavior. public function getCurrentAuthority() { instead of app('authority'); $this->currentAuthority = $this->currentAuthority ?: app('UserAuthority', [$this->getCurrentAccount()]); return $this->currentAuthority; } Notice it is important to cache the authority object so it is not recreated every time.
public getCurrentAuthority ( )

getCurrentUser() public method

public getCurrentUser ( )

getParams() public method

}
public getParams ( )

loadAndAuthorizeResource() public method

class BooksController extends Controller { public function __construct() { $this->loadAndAuthorizeResource(); } }
public loadAndAuthorizeResource ( $args = null )

loadResource() public method

For example, given an ArticlesController it will load the current article into the @article instance variable. It does this by either calling Article->find($this->params['id']); or new Article($this->params['article']); depending upon the action. The index action will automatically set $this->articles to Article::get(); or Article::$options['collectionScope']()->get(); If a conditional callback is used in the Authority, the 'create' and 'store' actions will set the initial attributes based on these conditions. This way these actions will satisfy the authority restrictions. Call this method directly on the controller class. class BooksController extends Controller { public function __construct() { $this->loadAndAuthorizeResource(); } } A resource is not loaded if the instance variable is already set. This makes it easy to override the behavior through a beforeFilter() on certain actions. class BooksController extends Controller { public function __construct() { $this->beforeFilter('findBookByPermalink', ['only' => 'show']); $this->loadAndAuthorizeResource(); } protected function findBookByPermalink() { $this->book = Book::where('permalink', $this->params['id'])->firstOrFail(); } } If a name is provided which does not match the controller it assumes it is a parent resource. Child resources can then be loaded through it. class BooksController extends Controller { public function __construct() { $this->loadResource('author'); $this->loadResource('book', ['through' => 'author']); } } Here the author resource will be loaded before each action using $this->params['author_id']. The book resource will then be loaded through the $this->author instance variable. That first argument is optional and will default to the singular name of the controller. A hash of options (see below) can also be passed to this method to further customize it. See loadAndAuthorizeResource() to automatically authorize the resource too. Options: ['only'] Only applies before filter to given actions. ['except'] Does not apply before filter to given actions. ['through'] Load this resource through another one. This should match the name of the parent instance variable or method. ['throughAssociation'] The name of the association to fetch the child records through the parent resource. This is normally not needed because it defaults to the pluralized resource name. ['shallow'] Pass true to allow this resource to be loaded directly when parent is null. Defaults to false. ['singleton'] Pass true if this is a singleton resource through a hasOne association. ['parent'] True or false depending on if the resource is considered a parent resource. This defaults to true if a resource name is given which does not match the controller. ['class'] The class to use for the model (string). ['instanceName'] The name of the instance variable to load the resource into. ['findBy'] Find using a different attribute other than id. For example. $this->loadResource(['findBy' => 'permalink']); will use where('permalink', $this->params['id'])->firstOrFail() ['idParam'] Find using a param key other than 'id'. For example: $this->loadResource(['idParam' => 'url']); // will use find($this->params['url']) ['collection'] Specify which actions are resource collection actions in addition to index. This is usually not necessary because it will try to guess depending on if the id param is present. $this->loadResource(['collection' => ['sort', 'list']]); ['create'] Specify which actions are new resource actions in addition to new, create and store. Pass an action name into here if you would like to build a new resource instead of fetch one. $this->loadResource(['create' => 'build']); ['collectionScope'] The name of the query scope to fetch the collection records of collection actions (E.g. index action). $this->loadResource(['collectionScope' => 'scopePopular']); // will use Article::popular()->get(); to fetch records of collection actions You can pass parameters with an array. For example: $this->loadResource(['collectionScope' => ['scopeOfType', 'published']]); // will use Article::ofType('published')->get(); By default, collection actions (index action) returns all the collection record with: Article::get(); // which is equivalent to Article::get(); ['prepend'] Passing true will use prependBeforeFilter() instead of a normal beforeFilter().
public loadResource ( $args = null )

methodExcludedByOptions() protected method

Determine if the given options exclude a particular method.
protected methodExcludedByOptions ( string $method, array $options ) : boolean
$method string
$options array
return boolean

paramsBeforeFilter() public method

public paramsBeforeFilter ( $filter, array $options = [] )
$options array

parseFilter() protected method

Parse the given filter and options.
protected parseFilter ( string $filter, array $options ) : array
$filter string
$options array
return array

prependAfterFilter() public method

Register a new "after" filter before any "after" filters on the controller.
public prependAfterFilter ( string $filter, array $options = [] ) : void
$filter string
$options array
return void

prependBeforeFilter() public method

Register a new "before" filter before any "before" filters on the controller.
public prependBeforeFilter ( string $filter, array $options = [] ) : void
$filter string
$options array
return void

removeFilter() protected method

Remove the given controller filter from the provided filter array.
protected removeFilter ( string $removing, array $current ) : array
$removing string
$current array
return array

setCurrentAbility() public method

alias of setCurrentAuthority() to match CanCan API
public setCurrentAbility ( $ability )

setCurrentAuthority() public method

public setCurrentAuthority ( $authority )

Property Details

$_authorized protected property

protected $_authorized

$afterFilters protected property

The "after" filters registered on the controller.
protected array $afterFilters
return array

$beforeFilters protected property

The "before" filters registered on the controller.
protected array $beforeFilters
return array

$currentAuthority protected property

Sadly, we can't set an empty array as default value here, maybe a PHP Trait bug ?
protected $currentAuthority

$currentUser protected property

protected $currentUser

$params protected property

protected $params