Skip to content

Commit

Permalink
[5.x] Add hook to query on entries listing (#10479)
Browse files Browse the repository at this point in the history
Co-authored-by: duncanmcclean <[email protected]>
Co-authored-by: Jason Varga <[email protected]>
  • Loading branch information
3 people authored Jul 18, 2024
1 parent ed1d8f4 commit a96a6a1
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 1 deletion.
25 changes: 25 additions & 0 deletions src/Hooks/CP/EntriesIndexQuery.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace Statamic\Hooks\CP;

use Statamic\Support\Traits\Hookable;

class EntriesIndexQuery
{
use Hookable;

public function __construct(private $query, private $collection)
{
//
}

public function paginate(?int $perPage)
{
$payload = $this->runHooksWith('query', [
'query' => $this->query,
'collection' => $this->collection,
]);

return $payload->query->paginate($perPage);
}
}
21 changes: 21 additions & 0 deletions src/Hooks/Payload.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

namespace Statamic\Hooks;

class Payload
{
public function __construct(private array $payload)
{
//
}

public function __get($key)
{
return $this->payload[$key] ?? null;
}

public function __set($key, $value)
{
$this->payload[$key] = $value;
}
}
3 changes: 2 additions & 1 deletion src/Http/Controllers/CP/Collections/EntriesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use Statamic\Facades\Site;
use Statamic\Facades\Stache;
use Statamic\Facades\User;
use Statamic\Hooks\CP\EntriesIndexQuery;
use Statamic\Http\Controllers\CP\CpController;
use Statamic\Http\Requests\FilteredRequest;
use Statamic\Http\Resources\CP\Entries\Entries;
Expand Down Expand Up @@ -49,7 +50,7 @@ public function index(FilteredRequest $request, $collection)
$query->orderBy($sortField, $sortDirection);
}

$entries = $query->paginate(request('perPage'));
$entries = (new EntriesIndexQuery($query, $collection))->paginate(request('perPage'));

if (request('search') && $collection->hasSearchIndex()) {
$entries->setCollection($entries->getCollection()->map->getSearchable());
Expand Down
6 changes: 6 additions & 0 deletions src/Support/Traits/Hookable.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Closure;
use Illuminate\Pipeline\Pipeline;
use Statamic\Hooks\Payload;

trait Hookable
{
Expand Down Expand Up @@ -46,4 +47,9 @@ protected function runHooks(string $name, $payload = null)
->through($closures->all())
->thenReturn();
}

protected function runHooksWith(string $name, array $payload)
{
return $this->runHooks($name, new Payload($payload));
}
}

0 comments on commit a96a6a1

Please sign in to comment.