# Perimeters

> A perimeter is one access rule of a control. allowed() is the permission, query() gives the rows for the lists, should() checks one row.

## The three callbacks

A perimeter declares one access rule: which users it applies to, and which rows it reaches.

```php
use App\Access\Perimeters\OwnPerimeter;
use App\Models\Post;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Lomkit\Access\Ability;

OwnPerimeter::new()
    ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} own posts"))
    ->should(fn (User $user, Post $post) => $post->author_id === $user->id)
    ->query(function (Builder $query, User $user): void {
        $query->where('author_id', $user->id);
    });
```

<table>
<thead>
  <tr>
    <th>
      Callback
    </th>
    
    <th>
      Question
    </th>
    
    <th>
      Used by
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        allowed()
      </code>
    </td>
    
    <td>
      Does the perimeter apply to this user, for this ability? The <strong>
        permission
      </strong>
      
      .
    </td>
    
    <td>
      everything
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        query()
      </code>
    </td>
    
    <td>
      Which rows does it reach? Constraints on the query, for the <strong>
        lists
      </strong>
      
      .
    </td>
    
    <td>
      <code>
        controlled()
      </code>
      
      , and the row check when there is no <code>
        should()
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        should()
      </code>
    </td>
    
    <td>
      Is this row one of them? The <strong>
        row check
      </strong>
      
      , in memory. Optional.
    </td>
    
    <td>
      the policy, and the rows about to be created (drafts)
    </td>
  </tr>
</tbody>
</table>

Take a user who may only see their own posts. `allowed()` says that they hold the `view own posts` permission. `should()` checks, in the policy, that the post at hand belongs to them. `query()` gives their posts for the lists.

`query()` and `should()` are two rules you write, so they must describe the same rows. `assertControlAgrees()` proves it on your test data, see [Testing](/testing-and-tooling/testing#the-decisions).

The user that the callbacks receive is the **reader**: any Eloquent model, such as a `User` or an API client. A perimeter whose callbacks type the reader, such as `fn (User $user, ...)`, applies only to the readers of that type. See [Readers](/essentials/readers#readers-of-several-types).

### `allowed()`

```php
->allowed(fn (User $user, Ability $ability) => $user->client_id !== null && $user->can("{$ability} client posts"))
```

- It receives the user and the ability. The ability converts to its name in a string: `"{$ability} client posts"` reads `view client posts`, `update client posts`, `approve client posts`.
- It must return a boolean: any other value throws `PerimeterCallbackResultException`.
- It never sees a row. A condition on the row goes in `should()` and `query()`, or in the [boundary](/essentials/boundaries).
- It runs at most once per reader, ability and decision context until the next write, whatever the number of rows, and the policy, the queries and the search share its answer. See [Readers](/essentials/readers#kept-decisions).

### `query()`

```php
->query(function (Builder $query, User $user, Ability $ability): void {
    $query->where('client_id', $user->client_id);
})
```

- It constrains the builder it receives and returns nothing. An arrow function that returns that same builder works too.
- Laravel turns `where('client_id', null)` into `IS NULL`. Refuse in `allowed()` a reader without the value, as above, so that a `null` never matches the rows without one.
- Returning another builder, such as `Post::query()->where(...)`, throws `QueryCallbackReturnedAnotherBuilderException`.
- A callback that adds no `where`, or only orders, limits or skips its constraint under a condition, throws `EmptyQueryCallbackException`. For every row, use [`unrestricted()`](#unrestricted-perimeters). For a user who reaches no row, refuse them in `allowed()`, or add `$query->whereRaw('0=1')`.
- A join throws `JoinInPerimeterException`, since Laravel drops the joins of a nested `where` group. Use `whereHas()` or an `exists` subquery.
- The ability, the third parameter, is optional. The controlled queries pass the ability they list: `view`, unless `controlled('update')` names another one.

### `should()`

```php
->should(fn (User $user, Post $post, Ability $ability) => $post->author_id === $user->id)
```

- It receives the user, the row and, optionally, the ability, and must return a boolean.
- It is optional. Without it, the policy checks a saved row through `query()`, in one SQL query on the row's key. With it, the row is checked in memory, without a query.
- A row about to be created, a **draft**, is not in the database: only `should()` can judge it. Keep `should()` on the perimeters through which users create rows. See [Policies](/essentials/policies#drafts).
- The policy passes the row as it is stored: after `fill()`, `should()` receives the original values. See [Policies](/essentials/policies#decisions-on-the-stored-row).

Drop a `should()` that only repeats its `query()` when no user creates rows through the perimeter and the extra query per check does not matter: the row is then checked in SQL.

## The ability

Each callback receives a `Lomkit\Access\Ability`, an immutable value object:

```php
use Lomkit\Access\Ability;

Ability::view();           // also create(), update(), delete(), restore(), forceDelete()
Ability::of('approve');    // any business ability
$ability->is('view');      // compare by name, with a string or an Ability
$ability->name();          // 'view'
"{$ability} posts";        // 'view posts'
```

- Type the ability parameter `Ability $ability`. An untyped parameter, or one typed `string`, throws `AbilityParameterTypeException` when the perimeter is declared. `?Ability`, `Stringable`, `object`, `mixed` and unions that contain `Ability` are accepted.
- Compare with `is()`, never with `===`: two abilities with the same name are two objects.
- A callback that does not need the ability leaves the parameter out: `fn (User $user) => $user->is_editor`.

The policy method `viewAny` maps to `view`, the other standard methods to themselves, and any other method to `Ability::of($method)`. See [Policies](/essentials/policies#abilities).

A perimeter can reach the posts of the user's client for `view`, and only the user's own posts of that client for the other abilities:

```php
ClientPerimeter::new()
    ->allowed(fn (User $user, Ability $ability) => $user->client_id !== null && $user->can("{$ability} client posts"))
    ->should(fn (User $user, Post $post, Ability $ability) => $ability->is('view')
        ? $post->client_id === $user->client_id
        : $post->client_id === $user->client_id && $post->author_id === $user->id)
    ->query(function (Builder $query, User $user, Ability $ability): void {
        $query->where('client_id', $user->client_id);

        if (! $ability->is('view')) {
            $query->where('author_id', $user->id);
        }
    });
```

## Unrestricted perimeters

A perimeter that reaches every row, such as an administrator's, is declared with `unrestricted()`:

```php
GlobalPerimeter::new()
    ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} all posts"))
    ->unrestricted();
```

- It takes only `allowed()`. Declaring `query()`, `should()` or search keys with it throws `UnrestrictedPerimeterCallbackException`.
- When it applies to the reader, the controlled queries get no perimeter constraint, the policy grants the row without any `should()`, and no other perimeter narrows it.
- The [boundary](/essentials/boundaries) of the control still applies.

<note>

Without a boundary, an unrestricted perimeter reaches the rows of every tenant. When your rows belong to tenants, keep each user inside theirs with a [boundary](/essentials/boundaries).

</note>

Never write a perimeter for every row as a `query()` that adds nothing: it throws `EmptyQueryCallbackException`.

## Perimeter classes

`OwnPerimeter`, `ClientPerimeter` and `GlobalPerimeter` above are classes of your application that extend `Lomkit\Access\Perimeters\Perimeter`, generated with `php artisan make:perimeter`. A class can also hold its rules itself, in protected hooks, and take a value for each use. See [Perimeter classes](/essentials/perimeter-classes).

## Perimeters are immutable

`allowed()`, `should()`, `query()`, `searchKeys()` and `unrestricted()` return a new perimeter and leave the one they are called on unchanged. Chain the declarations, or keep the returned perimeter:

```php
// Lost: the perimeter in $own has no callback
$own = OwnPerimeter::new();
$own->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} own posts"));

// Kept
$own = OwnPerimeter::new()
    ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} own posts"));
```

Each callback is declared once: a second `allowed()`, `should()`, `query()` or `searchKeys()` on one perimeter throws `DuplicatePerimeterCallbackException`. Write one callback that checks both conditions.

## Search keys

A perimeter of a searchable model also declares how it is searched, with `searchKeys()`, at the end of its chain. See [Search keys](/search/overview#search-keys).
