# Row context

> Decide the parent of a ThroughParent in the brand or tenant of each child row with decidedInRowContext() and Access::rowContextUsing(), and test the switch.

A [`ThroughParent`](/essentials/parents) decides its parent under the decision context of the request. When the control of the parent reads several brands from that context, a child row can be opened by a parent readable only in another brand than its own: [Several brands](/digging-deeper/several-brands#a-child-read-through-its-parent) shows the case. `decidedInRowContext()` decides the parent, for each child row, within the value that the row holds. Replace "brand" with the dimension of your application.

## Declaring the switch

Declare once, in the `boot()` method of a service provider and next to `Access::decisionContextUsing()`, the values that the request covers and how the application acts in one of them. `Brands` stands for the state of your application:

```php [app/Providers/AppServiceProvider.php]
use Closure;
use Lomkit\Access\Access;

public function boot(): void
{
    Access::decisionContextUsing(fn (): array => ['brands' => Brands::requested()->sort()->implode(',')]);

    Access::rowContextUsing(
        values: fn (): array => Brands::requested()->all(),
        within: fn (int|string $brand, Closure $decide): mixed => Brands::actingIn([$brand], $decide),
    );
}
```

```php
public static function actingIn(array $brands, Closure $callback): mixed
{
    $previous = self::$requested;
    self::$requested = $brands;

    try {
        return $callback();
    } finally {
        self::$requested = $previous;
    }
}
```

- `values` returns the values that the request covers, ints or non-empty strings, exactly as stored in the column of the child rows; an empty list reaches nothing. It must read the same state as the decision context.
- `within` switches the application to the single value it receives, every state that the parent reads included (the brands, the team of a permission package, a tenant), calls `$decide` exactly once, and restores the previous state in a `finally` block.
- Keep both cheap: they run once per value for each list, and for the first row check of a reader, ability and context in a request.
- Only the PHP state is switched: `within` runs while the package builds the SQL, and the query runs after it returns. Keep out of the rules of the parent a state that the database reads, such as a session variable or a row-level security policy.

Then name, on the `ThroughParent`, the column of the child row that holds the value:

```php [app/Access/Controls/CommentControl.php]
ThroughParent::belongsTo('post', inverse: 'comments')
    ->decidedInRowContext('brand_id'),
```

## What it changes

The SQL gets one branch per value of the request, each built while `within()` runs for its value:

```sql
where (
     (comments.brand_id = 'A' and exists (select * from posts where posts.id = comments.post_id and (<PostControl within A>)))
  or (comments.brand_id = 'B' and exists (select * from posts where posts.id = comments.post_id and (<PostControl within B>)))
)
```

- A child row whose value is `null`, or not one of `values`, has no branch: the `ThroughParent` refuses it. Reach such rows through another perimeter.
- The policy, the row checks, `withAbilities()`, `Access::preload()` and `reachableKeys()` use the same branches.
- A decision without a row is granted when there is a value of the request in which the `allowed()` of the `ThroughParent` accepts and the parent reaches a perimeter.
- A draft reads the column from its attributes, like the foreign key.
- The decisions on the parent are kept under the context of each value, the same key as a request of that value alone.
- `access:check` prints `row context brand_id` on the line of the `ThroughParent`, and `--json` gives `parent.row_context`.

Each row gets the answer of its own value alone. That narrows the wide answer only when the rules of the parent grow with the brands: each rule that reads the brands filters the rows by them, and each `allowed()` that reads them accepts as soon as the reader holds the right in one of them. A rule that grants more for fewer brands would open, within one value, a parent that the whole request does not open. No assertion checks it.

## Searching through the parent

A searchable child whose `ThroughParent` is `decidedInRowContext('brand_id')` writes the value of the child row after the relation: `through.post.in.1.2.workspace_id.1.author.7` for a comment of brand 1. A child without a value carries no key through that parent. The reader gets, for each value of the request where the `allowed()` of the `ThroughParent` accepts, the keys of the parent computed within that value. See [Searching through a parent](/search/through-a-parent).

## Errors

<table>
<thead>
  <tr>
    <th>
      Mistake
    </th>
    
    <th>
      Exception
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        decidedInRowContext()
      </code>
      
       without <code>
        Access::rowContextUsing()
      </code>
    </td>
    
    <td>
      <code>
        MissingRowContextException
      </code>
      
      , when the control is built
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        values
      </code>
      
       returns something else than a list of ints and non-empty strings
    </td>
    
    <td>
      <code>
        InvalidRowContextValuesException
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        within
      </code>
      
       does not call <code>
        $decide
      </code>
      
       exactly once, leaves the decision context changed, decides under the context of the whole request or of another value, or switches two values to the same context
    </td>
    
    <td>
      <code>
        RowContextSwitchException
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      The column is not a plain column name
    </td>
    
    <td>
      <code>
        InvalidRowContextColumnException
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        decidedInRowContext()
      </code>
      
       twice on one <code>
        ThroughParent
      </code>
    </td>
    
    <td>
      <code>
        DuplicatePerimeterCallbackException
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      The <code>
        ThroughParent
      </code>
      
       is a level of <code>
        Levels::of()
      </code>
    </td>
    
    <td>
      <code>
        RowContextInLevelsException
      </code>
      
      : declare it next to the group
    </td>
  </tr>
</tbody>
</table>

## Testing the switch

`assertRowContextAgrees()` compares each row with a request of its value alone, which the test sets up itself through `alone`, without the `within` closure under test:

```php
public function test_the_brand_switch_is_complete(): void
{
    foreach ([$this->headquarters, $this->brandManager] as $reader) {
        $this->assertRowContextAgrees(
            CommentControl::class,
            $reader,
            Comment::uncontrolled()->get(),
            alone: fn (int|string $brand, Closure $check): mixed => $this->asBrandRequest($brand, $check),
        );
    }
}
```

- `alone` receives a value and a callback, sets up every state of a real request of that value alone, calls the callback and restores the state. `asBrandRequest()` stands for that helper of your tests.
- For each row whose value is one of the request, the assertion compares the answer under the request with the answer inside `alone`, through the Gate and through `controlledFor()`, for `view`, `update` and `delete` by default (pass others as `abilities`).
- It catches a `within` that forgets a state the parent reads, and a perimeter or boundary of the child that reads the brands of the request instead of the brand of the row. It does not check that the rules of the parent grow with the brands.
- The control declares exactly one column with `decidedInRowContext()`, and at least one row holds a value of the request.
