Skip to content
5 changes: 5 additions & 0 deletions src/Query/ItemQueryBuilder.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,4 +19,9 @@ protected function getBaseItems()
{
return $this->items;
}

public function whereStatus($status)
{
return $this->where('status', $status);
}
}
2 changes: 1 addition & 1 deletion src/Query/Scopes/Filters/Status.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,7 +26,7 @@ public function fieldItems()

public function apply($query, $values)
{
$query->where('status', $values['status']);
$query->whereStatus($values['status']);
}

public function badge($values)
Expand Down
4 changes: 2 additions & 2 deletions src/Query/StatusQueryBuilder.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,7 +36,7 @@ public function __construct(Builder $builder, $status = 'published')
public function get($columns = ['*'])
{
if ($this->queryFallbackStatus) {
$this->builder->where('status', $this->fallbackStatus);
$this->builder->whereStatus($this->fallbackStatus);
}

return $this->builder->get($columns);
Expand All@@ -49,7 +49,7 @@ public function first()

public function __call($method, $parameters)
{
if (in_array($method, self::METHODS) && in_array(Arr::first($parameters), ['status', 'published'])) {
if ((in_array($method, self::METHODS) && in_array(Arr::first($parameters), ['status', 'published'])) || $method === 'whereStatus') {
$this->queryFallbackStatus = false;
}

Expand Down
76 changes: 75 additions & 1 deletion src/Stache/Query/EntryQueryBuilder.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,13 +5,16 @@
use Statamic\Contracts\Entries\QueryBuilder;
use Statamic\Entries\EntryCollection;
use Statamic\Facades;
use Statamic\Facades\Collection;
use Statamic\Support\Arr;

class EntryQueryBuilder extends Builder implements QueryBuilder
{
use QueriesTaxonomizedEntries;

protected $collections;
private const STATUSES = ['published', 'draft', 'scheduled', 'expired'];

protected $collections = [];

public function where($column, $operator = null, $value = null, $boolean = 'and')
{
Expand All@@ -21,6 +24,10 @@ public function where($column, $operator = null, $value = null, $boolean = 'and'
return $this;
}

if ($column === 'status') {
trigger_error('Filtering by status is deprecated. Use whereStatus() instead.', E_USER_DEPRECATED);
}

return parent::where($column, $operator, $value, $boolean);
}

Expand All@@ -32,6 +39,10 @@ public function whereIn($column, $values, $boolean = 'and')
return $this;
}

if ($column === 'status') {
trigger_error('Filtering by status is deprecated. Use whereStatus() instead.', E_USER_DEPRECATED);
}

return parent::whereIn($column, $values, $boolean);
}

Expand DownExpand Up@@ -133,6 +144,69 @@ protected function getWhereColumnKeyValuesByIndex($column)
});
}

public function whereStatus(string $status)
{
if (! in_array($status, self::STATUSES)) {
throw new \Exception("Invalid status [$status]");
}

if ($status === 'draft') {
return $this->where('published', false);
}

$this->where('published', true);

return $this->where(fn ($query) => $this
->getCollectionsForStatus()
->each(fn ($collection) => $query->orWhere(fn ($q) => $this->addCollectionStatusLogicToQuery($q, $status, $collection))));
}

private function getCollectionsForStatus()
{
// Since we have to add nested queries for each collection, if collections have been provided,
// we'll use those to avoid the need for adding unnecessary query clauses.

if (empty($this->collections)) {
return Collection::all();
}

return collect($this->collections)->map(fn ($handle) => Collection::find($handle));
}

private function addCollectionStatusLogicToQuery($query, $status, $collection)
{
// Using collectionHandle instead of collection because we intercept collection
// and put it on a property. In this case we actually want the indexed value.
// We can probably refactor this elsewhere later.
$query->where('collectionHandle', $collection->handle());

if ($collection->futureDateBehavior() === 'public' && $collection->pastDateBehavior() === 'public') {
if ($status === 'scheduled' || $status === 'expired') {
$query->where('date', 'invalid'); // intentionally trigger no results.
}
}

if ($collection->futureDateBehavior() === 'private') {
$status === 'scheduled'
? $query->where('date', '>', now())
: $query->where('date', '<', now());

if ($status === 'expired') {
$query->where('date', 'invalid'); // intentionally trigger no results.
}
}

if ($collection->pastDateBehavior() === 'private') {
$status === 'expired'
? $query->where('date', '<', now())
: $query->where('date', '>', now());

if ($status === 'scheduled') {
$query->where('date', 'invalid'); // intentionally trigger no results.
}
}
}

public function prepareForFakeQuery(): array
{
$data = parent::prepareForFakeQuery();
Expand Down
6 changes: 3 additions & 3 deletions src/Tags/Collection/Entries.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -184,7 +184,7 @@ protected function query()

$this->querySelect($query);
$this->querySite($query);
$this->queryStatus($query);
$this->queryPublished($query);
$this->queryPastFuture($query);
$this->querySinceUntil($query);
$this->queryTaxonomies($query);
Expand DownExpand Up@@ -270,13 +270,13 @@ protected function querySite($query)
return $query->where('site', $site);
}

protected function queryStatus($query)
protected function queryPublished($query)
{
if ($this->isQueryingCondition('status') || $this->isQueryingCondition('published')) {
return;
}

return $query->where('status', 'published');
return $query->where('published', true);
}

protected function queryPastFuture($query)
Expand Down
4 changes: 4 additions & 0 deletions src/Tags/Concerns/QueriesConditions.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -128,6 +128,10 @@ protected function queryCondition($query, $field, $condition, $value)

protected function queryIsCondition($query, $field, $value)
{
if ($field === 'status') {
return $query->whereStatus($value);
}

return $query->where($field, $value);
}

Expand Down
40 changes: 40 additions & 0 deletions tests/API/APITest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -99,6 +99,46 @@ public function it_filters_published_entries_by_default()
$this->assertEndpointNotFound('/api/collections/pages/entries/nectar');
}

/** @test */
public function it_filters_out_future_entries_from_future_private_collection()
{
Facades\Config::set('statamic.api.resources.collections', true);

Facades\Collection::make('test')->dated(true)
->pastDateBehavior('public')
->futureDateBehavior('private')
->save();

Facades\Entry::make()->collection('test')->id('a')->published(true)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('b')->published(false)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('c')->published(true)->date(now()->subDay())->save();
Facades\Entry::make()->collection('test')->id('d')->published(false)->date(now()->subDay())->save();

$response = $this->get('/api/collections/test/entries')->assertSuccessful();
$this->assertCount(1, $response->getData()->data);
$response->assertJsonPath('data.0.id', 'c');
}

/** @test */
public function it_filters_out_past_entries_from_past_private_collection()
{
Facades\Config::set('statamic.api.resources.collections', true);

Facades\Collection::make('test')->dated(true)
->pastDateBehavior('private')
->futureDateBehavior('public')
->save();

Facades\Entry::make()->collection('test')->id('a')->published(true)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('b')->published(false)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('c')->published(true)->date(now()->subDay())->save();
Facades\Entry::make()->collection('test')->id('d')->published(false)->date(now()->subDay())->save();

$response = $this->get('/api/collections/test/entries')->assertSuccessful();
$this->assertCount(1, $response->getData()->data);
$response->assertJsonPath('data.0.id', 'a');
}

/** @test */
public function it_can_filter_collection_entries_when_configuration_allows_for_it()
{
Expand Down
91 changes: 91 additions & 0 deletions tests/Data/Entries/EntryQueryBuilderTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -770,6 +770,97 @@ public function entries_are_found_using_lazy()
}

/** @test */
public function filtering_using_where_status_column_writes_deprecation_log()
{
$this->withoutDeprecationHandling();
$this->expectException(\ErrorException::class);
$this->expectExceptionMessage('Filtering by status is deprecated. Use whereStatus() instead.');

$this->createDummyCollectionAndEntries();

Entry::query()->where('collection', 'posts')->where('status', 'published')->get();
}

/** @test */
public function filtering_using_whereIn_status_column_writes_deprecation_log()
{
$this->withoutDeprecationHandling();
$this->expectException(\ErrorException::class);
$this->expectExceptionMessage('Filtering by status is deprecated. Use whereStatus() instead.');

$this->createDummyCollectionAndEntries();

Entry::query()->where('collection', 'posts')->whereIn('status', ['published'])->get();
}

/** @test */
public function filtering_by_unexpected_status_throws_exception()
{
$this->expectExceptionMessage('Invalid status [foo]');

Entry::query()->whereStatus('foo')->get();
}

/**
* @test
*
* @dataProvider filterByStatusProvider
*/
public function it_filters_by_status($status, $expected)
{
Collection::make('pages')->dated(false)->save();
EntryFactory::collection('pages')->id('page')->published(true)->create();
EntryFactory::collection('pages')->id('page-draft')->published(false)->create();

Collection::make('blog')->dated(true)->futureDateBehavior('private')->pastDateBehavior('public')->save();
EntryFactory::collection('blog')->id('blog-future')->published(true)->date(now()->addDay())->create();
EntryFactory::collection('blog')->id('blog-future-draft')->published(false)->date(now()->addDay())->create();
EntryFactory::collection('blog')->id('blog-past')->published(true)->date(now()->subDay())->create();
EntryFactory::collection('blog')->id('blog-past-draft')->published(false)->date(now()->subDay())->create();

Collection::make('events')->dated(true)->futureDateBehavior('public')->pastDateBehavior('private')->save();
EntryFactory::collection('events')->id('event-future')->published(true)->date(now()->addDay())->create();
EntryFactory::collection('events')->id('event-future-draft')->published(false)->date(now()->addDay())->create();
EntryFactory::collection('events')->id('event-past')->published(true)->date(now()->subDay())->create();
EntryFactory::collection('events')->id('event-past-draft')->published(false)->date(now()->subDay())->create();

Collection::make('calendar')->dated(true)->futureDateBehavior('public')->pastDateBehavior('public')->save();
EntryFactory::collection('calendar')->id('calendar-future')->published(true)->date(now()->addDay())->create();
EntryFactory::collection('calendar')->id('calendar-future-draft')->published(false)->date(now()->addDay())->create();
EntryFactory::collection('calendar')->id('calendar-past')->published(true)->date(now()->subDay())->create();
EntryFactory::collection('calendar')->id('calendar-past-draft')->published(false)->date(now()->subDay())->create();

$this->assertEquals($expected, Entry::query()->whereStatus($status)->get()->map->id->all());
}

public static function filterByStatusProvider()
{
return [
'draft' => ['draft', [
'page-draft',
'blog-future-draft',
'blog-past-draft',
'event-future-draft',
'event-past-draft',
'calendar-future-draft',
'calendar-past-draft',
]],
'published' => ['published', [
'page',
'blog-past',
'event-future',
'calendar-future',
'calendar-past',
]],
'scheduled' => ['scheduled', [
'blog-future',
]],
'expired' => ['expired', [
'event-past',
]],
];
}

public function values_can_be_plucked()
{
$this->createDummyCollectionAndEntries();
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
[5.x] Avoid querying status by jasonvarga · Pull Request #9317 · statamic/cms · GitHub
Skip to content
5 changes: 5 additions & 0 deletions src/Query/ItemQueryBuilder.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,4 +19,9 @@ protected function getBaseItems()
{
return $this->items;
}

public function whereStatus($status)
{
return $this->where('status', $status);
}
}
2 changes: 1 addition & 1 deletion src/Query/Scopes/Filters/Status.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,7 +26,7 @@ public function fieldItems()

public function apply($query, $values)
{
$query->where('status', $values['status']);
$query->whereStatus($values['status']);
}

public function badge($values)
Expand Down
4 changes: 2 additions & 2 deletions src/Query/StatusQueryBuilder.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,7 +36,7 @@ public function __construct(Builder $builder, $status = 'published')
public function get($columns = ['*'])
{
if ($this->queryFallbackStatus) {
$this->builder->where('status', $this->fallbackStatus);
$this->builder->whereStatus($this->fallbackStatus);
}

return $this->builder->get($columns);
Expand All@@ -49,7 +49,7 @@ public function first()

public function __call($method, $parameters)
{
if (in_array($method, self::METHODS) && in_array(Arr::first($parameters), ['status', 'published'])) {
if ((in_array($method, self::METHODS) && in_array(Arr::first($parameters), ['status', 'published'])) || $method === 'whereStatus') {
$this->queryFallbackStatus = false;
}

Expand Down
76 changes: 75 additions & 1 deletion src/Stache/Query/EntryQueryBuilder.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,13 +5,16 @@
use Statamic\Contracts\Entries\QueryBuilder;
use Statamic\Entries\EntryCollection;
use Statamic\Facades;
use Statamic\Facades\Collection;
use Statamic\Support\Arr;

class EntryQueryBuilder extends Builder implements QueryBuilder
{
use QueriesTaxonomizedEntries;

protected $collections;
private const STATUSES = ['published', 'draft', 'scheduled', 'expired'];

protected $collections = [];

public function where($column, $operator = null, $value = null, $boolean = 'and')
{
Expand All@@ -21,6 +24,10 @@ public function where($column, $operator = null, $value = null, $boolean = 'and'
return $this;
}

if ($column === 'status') {
trigger_error('Filtering by status is deprecated. Use whereStatus() instead.', E_USER_DEPRECATED);
}

return parent::where($column, $operator, $value, $boolean);
}

Expand All@@ -32,6 +39,10 @@ public function whereIn($column, $values, $boolean = 'and')
return $this;
}

if ($column === 'status') {
trigger_error('Filtering by status is deprecated. Use whereStatus() instead.', E_USER_DEPRECATED);
}

return parent::whereIn($column, $values, $boolean);
}

Expand DownExpand Up@@ -133,6 +144,69 @@ protected function getWhereColumnKeyValuesByIndex($column)
});
}

public function whereStatus(string $status)
{
if (! in_array($status, self::STATUSES)) {
throw new \Exception("Invalid status [$status]");
}

if ($status === 'draft') {
return $this->where('published', false);
}

$this->where('published', true);

return $this->where(fn ($query) => $this
->getCollectionsForStatus()
->each(fn ($collection) => $query->orWhere(fn ($q) => $this->addCollectionStatusLogicToQuery($q, $status, $collection))));
}

private function getCollectionsForStatus()
{
// Since we have to add nested queries for each collection, if collections have been provided,
// we'll use those to avoid the need for adding unnecessary query clauses.

if (empty($this->collections)) {
return Collection::all();
}

return collect($this->collections)->map(fn ($handle) => Collection::find($handle));
}

private function addCollectionStatusLogicToQuery($query, $status, $collection)
{
// Using collectionHandle instead of collection because we intercept collection
// and put it on a property. In this case we actually want the indexed value.
// We can probably refactor this elsewhere later.
$query->where('collectionHandle', $collection->handle());

if ($collection->futureDateBehavior() === 'public' && $collection->pastDateBehavior() === 'public') {
if ($status === 'scheduled' || $status === 'expired') {
$query->where('date', 'invalid'); // intentionally trigger no results.
}
}

if ($collection->futureDateBehavior() === 'private') {
$status === 'scheduled'
? $query->where('date', '>', now())
: $query->where('date', '<', now());

if ($status === 'expired') {
$query->where('date', 'invalid'); // intentionally trigger no results.
}
}

if ($collection->pastDateBehavior() === 'private') {
$status === 'expired'
? $query->where('date', '<', now())
: $query->where('date', '>', now());

if ($status === 'scheduled') {
$query->where('date', 'invalid'); // intentionally trigger no results.
}
}
}

public function prepareForFakeQuery(): array
{
$data = parent::prepareForFakeQuery();
Expand Down
6 changes: 3 additions & 3 deletions src/Tags/Collection/Entries.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -184,7 +184,7 @@ protected function query()

$this->querySelect($query);
$this->querySite($query);
$this->queryStatus($query);
$this->queryPublished($query);
$this->queryPastFuture($query);
$this->querySinceUntil($query);
$this->queryTaxonomies($query);
Expand DownExpand Up@@ -270,13 +270,13 @@ protected function querySite($query)
return $query->where('site', $site);
}

protected function queryStatus($query)
protected function queryPublished($query)
{
if ($this->isQueryingCondition('status') || $this->isQueryingCondition('published')) {
return;
}

return $query->where('status', 'published');
return $query->where('published', true);
}

protected function queryPastFuture($query)
Expand Down
4 changes: 4 additions & 0 deletions src/Tags/Concerns/QueriesConditions.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -128,6 +128,10 @@ protected function queryCondition($query, $field, $condition, $value)

protected function queryIsCondition($query, $field, $value)
{
if ($field === 'status') {
return $query->whereStatus($value);
}

return $query->where($field, $value);
}

Expand Down
40 changes: 40 additions & 0 deletions tests/API/APITest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -99,6 +99,46 @@ public function it_filters_published_entries_by_default()
$this->assertEndpointNotFound('/api/collections/pages/entries/nectar');
}

/** @test */
public function it_filters_out_future_entries_from_future_private_collection()
{
Facades\Config::set('statamic.api.resources.collections', true);

Facades\Collection::make('test')->dated(true)
->pastDateBehavior('public')
->futureDateBehavior('private')
->save();

Facades\Entry::make()->collection('test')->id('a')->published(true)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('b')->published(false)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('c')->published(true)->date(now()->subDay())->save();
Facades\Entry::make()->collection('test')->id('d')->published(false)->date(now()->subDay())->save();

$response = $this->get('/api/collections/test/entries')->assertSuccessful();
$this->assertCount(1, $response->getData()->data);
$response->assertJsonPath('data.0.id', 'c');
}

/** @test */
public function it_filters_out_past_entries_from_past_private_collection()
{
Facades\Config::set('statamic.api.resources.collections', true);

Facades\Collection::make('test')->dated(true)
->pastDateBehavior('private')
->futureDateBehavior('public')
->save();

Facades\Entry::make()->collection('test')->id('a')->published(true)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('b')->published(false)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('c')->published(true)->date(now()->subDay())->save();
Facades\Entry::make()->collection('test')->id('d')->published(false)->date(now()->subDay())->save();

$response = $this->get('/api/collections/test/entries')->assertSuccessful();
$this->assertCount(1, $response->getData()->data);
$response->assertJsonPath('data.0.id', 'a');
}

/** @test */
public function it_can_filter_collection_entries_when_configuration_allows_for_it()
{
Expand Down
91 changes: 91 additions & 0 deletions tests/Data/Entries/EntryQueryBuilderTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -770,6 +770,97 @@ public function entries_are_found_using_lazy()
}

/** @test */
public function filtering_using_where_status_column_writes_deprecation_log()
{
$this->withoutDeprecationHandling();
$this->expectException(\ErrorException::class);
$this->expectExceptionMessage('Filtering by status is deprecated. Use whereStatus() instead.');

$this->createDummyCollectionAndEntries();

Entry::query()->where('collection', 'posts')->where('status', 'published')->get();
}

/** @test */
public function filtering_using_whereIn_status_column_writes_deprecation_log()
{
$this->withoutDeprecationHandling();
$this->expectException(\ErrorException::class);
$this->expectExceptionMessage('Filtering by status is deprecated. Use whereStatus() instead.');

$this->createDummyCollectionAndEntries();

Entry::query()->where('collection', 'posts')->whereIn('status', ['published'])->get();
}

/** @test */
public function filtering_by_unexpected_status_throws_exception()
{
$this->expectExceptionMessage('Invalid status [foo]');

Entry::query()->whereStatus('foo')->get();
}

/**
* @test
*
* @dataProvider filterByStatusProvider
*/
public function it_filters_by_status($status, $expected)
{
Collection::make('pages')->dated(false)->save();
EntryFactory::collection('pages')->id('page')->published(true)->create();
EntryFactory::collection('pages')->id('page-draft')->published(false)->create();

Collection::make('blog')->dated(true)->futureDateBehavior('private')->pastDateBehavior('public')->save();
EntryFactory::collection('blog')->id('blog-future')->published(true)->date(now()->addDay())->create();
EntryFactory::collection('blog')->id('blog-future-draft')->published(false)->date(now()->addDay())->create();
EntryFactory::collection('blog')->id('blog-past')->published(true)->date(now()->subDay())->create();
EntryFactory::collection('blog')->id('blog-past-draft')->published(false)->date(now()->subDay())->create();

Collection::make('events')->dated(true)->futureDateBehavior('public')->pastDateBehavior('private')->save();
EntryFactory::collection('events')->id('event-future')->published(true)->date(now()->addDay())->create();
EntryFactory::collection('events')->id('event-future-draft')->published(false)->date(now()->addDay())->create();
EntryFactory::collection('events')->id('event-past')->published(true)->date(now()->subDay())->create();
EntryFactory::collection('events')->id('event-past-draft')->published(false)->date(now()->subDay())->create();

Collection::make('calendar')->dated(true)->futureDateBehavior('public')->pastDateBehavior('public')->save();
EntryFactory::collection('calendar')->id('calendar-future')->published(true)->date(now()->addDay())->create();
EntryFactory::collection('calendar')->id('calendar-future-draft')->published(false)->date(now()->addDay())->create();
EntryFactory::collection('calendar')->id('calendar-past')->published(true)->date(now()->subDay())->create();
EntryFactory::collection('calendar')->id('calendar-past-draft')->published(false)->date(now()->subDay())->create();

$this->assertEquals($expected, Entry::query()->whereStatus($status)->get()->map->id->all());
}

public static function filterByStatusProvider()
{
return [
'draft' => ['draft', [
'page-draft',
'blog-future-draft',
'blog-past-draft',
'event-future-draft',
'event-past-draft',
'calendar-future-draft',
'calendar-past-draft',
]],
'published' => ['published', [
'page',
'blog-past',
'event-future',
'calendar-future',
'calendar-past',
]],
'scheduled' => ['scheduled', [
'blog-future',
]],
'expired' => ['expired', [
'event-past',
]],
];
}

public function values_can_be_plucked()
{
$this->createDummyCollectionAndEntries();
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [5.x] Avoid querying status by jasonvarga · Pull Request #9317 · statamic/cms · GitHub
Skip to content
5 changes: 5 additions & 0 deletions src/Query/ItemQueryBuilder.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,4 +19,9 @@ protected function getBaseItems()
{
return $this->items;
}

public function whereStatus($status)
{
return $this->where('status', $status);
}
}
2 changes: 1 addition & 1 deletion src/Query/Scopes/Filters/Status.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,7 +26,7 @@ public function fieldItems()

public function apply($query, $values)
{
$query->where('status', $values['status']);
$query->whereStatus($values['status']);
}

public function badge($values)
Expand Down
4 changes: 2 additions & 2 deletions src/Query/StatusQueryBuilder.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,7 +36,7 @@ public function __construct(Builder $builder, $status = 'published')
public function get($columns = ['*'])
{
if ($this->queryFallbackStatus) {
$this->builder->where('status', $this->fallbackStatus);
$this->builder->whereStatus($this->fallbackStatus);
}

return $this->builder->get($columns);
Expand All@@ -49,7 +49,7 @@ public function first()

public function __call($method, $parameters)
{
if (in_array($method, self::METHODS) && in_array(Arr::first($parameters), ['status', 'published'])) {
if ((in_array($method, self::METHODS) && in_array(Arr::first($parameters), ['status', 'published'])) || $method === 'whereStatus') {
$this->queryFallbackStatus = false;
}

Expand Down
76 changes: 75 additions & 1 deletion src/Stache/Query/EntryQueryBuilder.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,13 +5,16 @@
use Statamic\Contracts\Entries\QueryBuilder;
use Statamic\Entries\EntryCollection;
use Statamic\Facades;
use Statamic\Facades\Collection;
use Statamic\Support\Arr;

class EntryQueryBuilder extends Builder implements QueryBuilder
{
use QueriesTaxonomizedEntries;

protected $collections;
private const STATUSES = ['published', 'draft', 'scheduled', 'expired'];

protected $collections = [];

public function where($column, $operator = null, $value = null, $boolean = 'and')
{
Expand All@@ -21,6 +24,10 @@ public function where($column, $operator = null, $value = null, $boolean = 'and'
return $this;
}

if ($column === 'status') {
trigger_error('Filtering by status is deprecated. Use whereStatus() instead.', E_USER_DEPRECATED);
}

return parent::where($column, $operator, $value, $boolean);
}

Expand All@@ -32,6 +39,10 @@ public function whereIn($column, $values, $boolean = 'and')
return $this;
}

if ($column === 'status') {
trigger_error('Filtering by status is deprecated. Use whereStatus() instead.', E_USER_DEPRECATED);
}

return parent::whereIn($column, $values, $boolean);
}

Expand DownExpand Up@@ -133,6 +144,69 @@ protected function getWhereColumnKeyValuesByIndex($column)
});
}

public function whereStatus(string $status)
{
if (! in_array($status, self::STATUSES)) {
throw new \Exception("Invalid status [$status]");
}

if ($status === 'draft') {
return $this->where('published', false);
}

$this->where('published', true);

return $this->where(fn ($query) => $this
->getCollectionsForStatus()
->each(fn ($collection) => $query->orWhere(fn ($q) => $this->addCollectionStatusLogicToQuery($q, $status, $collection))));
}

private function getCollectionsForStatus()
{
// Since we have to add nested queries for each collection, if collections have been provided,
// we'll use those to avoid the need for adding unnecessary query clauses.

if (empty($this->collections)) {
return Collection::all();
}

return collect($this->collections)->map(fn ($handle) => Collection::find($handle));
}

private function addCollectionStatusLogicToQuery($query, $status, $collection)
{
// Using collectionHandle instead of collection because we intercept collection
// and put it on a property. In this case we actually want the indexed value.
// We can probably refactor this elsewhere later.
$query->where('collectionHandle', $collection->handle());

if ($collection->futureDateBehavior() === 'public' && $collection->pastDateBehavior() === 'public') {
if ($status === 'scheduled' || $status === 'expired') {
$query->where('date', 'invalid'); // intentionally trigger no results.
}
}

if ($collection->futureDateBehavior() === 'private') {
$status === 'scheduled'
? $query->where('date', '>', now())
: $query->where('date', '<', now());

if ($status === 'expired') {
$query->where('date', 'invalid'); // intentionally trigger no results.
}
}

if ($collection->pastDateBehavior() === 'private') {
$status === 'expired'
? $query->where('date', '<', now())
: $query->where('date', '>', now());

if ($status === 'scheduled') {
$query->where('date', 'invalid'); // intentionally trigger no results.
}
}
}

public function prepareForFakeQuery(): array
{
$data = parent::prepareForFakeQuery();
Expand Down
6 changes: 3 additions & 3 deletions src/Tags/Collection/Entries.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -184,7 +184,7 @@ protected function query()

$this->querySelect($query);
$this->querySite($query);
$this->queryStatus($query);
$this->queryPublished($query);
$this->queryPastFuture($query);
$this->querySinceUntil($query);
$this->queryTaxonomies($query);
Expand DownExpand Up@@ -270,13 +270,13 @@ protected function querySite($query)
return $query->where('site', $site);
}

protected function queryStatus($query)
protected function queryPublished($query)
{
if ($this->isQueryingCondition('status') || $this->isQueryingCondition('published')) {
return;
}

return $query->where('status', 'published');
return $query->where('published', true);
}

protected function queryPastFuture($query)
Expand Down
4 changes: 4 additions & 0 deletions src/Tags/Concerns/QueriesConditions.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -128,6 +128,10 @@ protected function queryCondition($query, $field, $condition, $value)

protected function queryIsCondition($query, $field, $value)
{
if ($field === 'status') {
return $query->whereStatus($value);
}

return $query->where($field, $value);
}

Expand Down
40 changes: 40 additions & 0 deletions tests/API/APITest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -99,6 +99,46 @@ public function it_filters_published_entries_by_default()
$this->assertEndpointNotFound('/api/collections/pages/entries/nectar');
}

/** @test */
public function it_filters_out_future_entries_from_future_private_collection()
{
Facades\Config::set('statamic.api.resources.collections', true);

Facades\Collection::make('test')->dated(true)
->pastDateBehavior('public')
->futureDateBehavior('private')
->save();

Facades\Entry::make()->collection('test')->id('a')->published(true)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('b')->published(false)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('c')->published(true)->date(now()->subDay())->save();
Facades\Entry::make()->collection('test')->id('d')->published(false)->date(now()->subDay())->save();

$response = $this->get('/api/collections/test/entries')->assertSuccessful();
$this->assertCount(1, $response->getData()->data);
$response->assertJsonPath('data.0.id', 'c');
}

/** @test */
public function it_filters_out_past_entries_from_past_private_collection()
{
Facades\Config::set('statamic.api.resources.collections', true);

Facades\Collection::make('test')->dated(true)
->pastDateBehavior('private')
->futureDateBehavior('public')
->save();

Facades\Entry::make()->collection('test')->id('a')->published(true)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('b')->published(false)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('c')->published(true)->date(now()->subDay())->save();
Facades\Entry::make()->collection('test')->id('d')->published(false)->date(now()->subDay())->save();

$response = $this->get('/api/collections/test/entries')->assertSuccessful();
$this->assertCount(1, $response->getData()->data);
$response->assertJsonPath('data.0.id', 'a');
}

/** @test */
public function it_can_filter_collection_entries_when_configuration_allows_for_it()
{
Expand Down
91 changes: 91 additions & 0 deletions tests/Data/Entries/EntryQueryBuilderTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -770,6 +770,97 @@ public function entries_are_found_using_lazy()
}

/** @test */
public function filtering_using_where_status_column_writes_deprecation_log()
{
$this->withoutDeprecationHandling();
$this->expectException(\ErrorException::class);
$this->expectExceptionMessage('Filtering by status is deprecated. Use whereStatus() instead.');

$this->createDummyCollectionAndEntries();

Entry::query()->where('collection', 'posts')->where('status', 'published')->get();
}

/** @test */
public function filtering_using_whereIn_status_column_writes_deprecation_log()
{
$this->withoutDeprecationHandling();
$this->expectException(\ErrorException::class);
$this->expectExceptionMessage('Filtering by status is deprecated. Use whereStatus() instead.');

$this->createDummyCollectionAndEntries();

Entry::query()->where('collection', 'posts')->whereIn('status', ['published'])->get();
}

/** @test */
public function filtering_by_unexpected_status_throws_exception()
{
$this->expectExceptionMessage('Invalid status [foo]');

Entry::query()->whereStatus('foo')->get();
}

/**
* @test
*
* @dataProvider filterByStatusProvider
*/
public function it_filters_by_status($status, $expected)
{
Collection::make('pages')->dated(false)->save();
EntryFactory::collection('pages')->id('page')->published(true)->create();
EntryFactory::collection('pages')->id('page-draft')->published(false)->create();

Collection::make('blog')->dated(true)->futureDateBehavior('private')->pastDateBehavior('public')->save();
EntryFactory::collection('blog')->id('blog-future')->published(true)->date(now()->addDay())->create();
EntryFactory::collection('blog')->id('blog-future-draft')->published(false)->date(now()->addDay())->create();
EntryFactory::collection('blog')->id('blog-past')->published(true)->date(now()->subDay())->create();
EntryFactory::collection('blog')->id('blog-past-draft')->published(false)->date(now()->subDay())->create();

Collection::make('events')->dated(true)->futureDateBehavior('public')->pastDateBehavior('private')->save();
EntryFactory::collection('events')->id('event-future')->published(true)->date(now()->addDay())->create();
EntryFactory::collection('events')->id('event-future-draft')->published(false)->date(now()->addDay())->create();
EntryFactory::collection('events')->id('event-past')->published(true)->date(now()->subDay())->create();
EntryFactory::collection('events')->id('event-past-draft')->published(false)->date(now()->subDay())->create();

Collection::make('calendar')->dated(true)->futureDateBehavior('public')->pastDateBehavior('public')->save();
EntryFactory::collection('calendar')->id('calendar-future')->published(true)->date(now()->addDay())->create();
EntryFactory::collection('calendar')->id('calendar-future-draft')->published(false)->date(now()->addDay())->create();
EntryFactory::collection('calendar')->id('calendar-past')->published(true)->date(now()->subDay())->create();
EntryFactory::collection('calendar')->id('calendar-past-draft')->published(false)->date(now()->subDay())->create();

$this->assertEquals($expected, Entry::query()->whereStatus($status)->get()->map->id->all());
}

public static function filterByStatusProvider()
{
return [
'draft' => ['draft', [
'page-draft',
'blog-future-draft',
'blog-past-draft',
'event-future-draft',
'event-past-draft',
'calendar-future-draft',
'calendar-past-draft',
]],
'published' => ['published', [
'page',
'blog-past',
'event-future',
'calendar-future',
'calendar-past',
]],
'scheduled' => ['scheduled', [
'blog-future',
]],
'expired' => ['expired', [
'event-past',
]],
];
}

public function values_can_be_plucked()
{
$this->createDummyCollectionAndEntries();
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [5.x] Avoid querying status by jasonvarga · Pull Request #9317 · statamic/cms · GitHub
Skip to content
5 changes: 5 additions & 0 deletions src/Query/ItemQueryBuilder.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,4 +19,9 @@ protected function getBaseItems()
{
return $this->items;
}

public function whereStatus($status)
{
return $this->where('status', $status);
}
}
2 changes: 1 addition & 1 deletion src/Query/Scopes/Filters/Status.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,7 +26,7 @@ public function fieldItems()

public function apply($query, $values)
{
$query->where('status', $values['status']);
$query->whereStatus($values['status']);
}

public function badge($values)
Expand Down
4 changes: 2 additions & 2 deletions src/Query/StatusQueryBuilder.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,7 +36,7 @@ public function __construct(Builder $builder, $status = 'published')
public function get($columns = ['*'])
{
if ($this->queryFallbackStatus) {
$this->builder->where('status', $this->fallbackStatus);
$this->builder->whereStatus($this->fallbackStatus);
}

return $this->builder->get($columns);
Expand All@@ -49,7 +49,7 @@ public function first()

public function __call($method, $parameters)
{
if (in_array($method, self::METHODS) && in_array(Arr::first($parameters), ['status', 'published'])) {
if ((in_array($method, self::METHODS) && in_array(Arr::first($parameters), ['status', 'published'])) || $method === 'whereStatus') {
$this->queryFallbackStatus = false;
}

Expand Down
76 changes: 75 additions & 1 deletion src/Stache/Query/EntryQueryBuilder.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,13 +5,16 @@
use Statamic\Contracts\Entries\QueryBuilder;
use Statamic\Entries\EntryCollection;
use Statamic\Facades;
use Statamic\Facades\Collection;
use Statamic\Support\Arr;

class EntryQueryBuilder extends Builder implements QueryBuilder
{
use QueriesTaxonomizedEntries;

protected $collections;
private const STATUSES = ['published', 'draft', 'scheduled', 'expired'];

protected $collections = [];

public function where($column, $operator = null, $value = null, $boolean = 'and')
{
Expand All@@ -21,6 +24,10 @@ public function where($column, $operator = null, $value = null, $boolean = 'and'
return $this;
}

if ($column === 'status') {
trigger_error('Filtering by status is deprecated. Use whereStatus() instead.', E_USER_DEPRECATED);
}

return parent::where($column, $operator, $value, $boolean);
}

Expand All@@ -32,6 +39,10 @@ public function whereIn($column, $values, $boolean = 'and')
return $this;
}

if ($column === 'status') {
trigger_error('Filtering by status is deprecated. Use whereStatus() instead.', E_USER_DEPRECATED);
}

return parent::whereIn($column, $values, $boolean);
}

Expand DownExpand Up@@ -133,6 +144,69 @@ protected function getWhereColumnKeyValuesByIndex($column)
});
}

public function whereStatus(string $status)
{
if (! in_array($status, self::STATUSES)) {
throw new \Exception("Invalid status [$status]");
}

if ($status === 'draft') {
return $this->where('published', false);
}

$this->where('published', true);

return $this->where(fn ($query) => $this
->getCollectionsForStatus()
->each(fn ($collection) => $query->orWhere(fn ($q) => $this->addCollectionStatusLogicToQuery($q, $status, $collection))));
}

private function getCollectionsForStatus()
{
// Since we have to add nested queries for each collection, if collections have been provided,
// we'll use those to avoid the need for adding unnecessary query clauses.

if (empty($this->collections)) {
return Collection::all();
}

return collect($this->collections)->map(fn ($handle) => Collection::find($handle));
}

private function addCollectionStatusLogicToQuery($query, $status, $collection)
{
// Using collectionHandle instead of collection because we intercept collection
// and put it on a property. In this case we actually want the indexed value.
// We can probably refactor this elsewhere later.
$query->where('collectionHandle', $collection->handle());

if ($collection->futureDateBehavior() === 'public' && $collection->pastDateBehavior() === 'public') {
if ($status === 'scheduled' || $status === 'expired') {
$query->where('date', 'invalid'); // intentionally trigger no results.
}
}

if ($collection->futureDateBehavior() === 'private') {
$status === 'scheduled'
? $query->where('date', '>', now())
: $query->where('date', '<', now());

if ($status === 'expired') {
$query->where('date', 'invalid'); // intentionally trigger no results.
}
}

if ($collection->pastDateBehavior() === 'private') {
$status === 'expired'
? $query->where('date', '<', now())
: $query->where('date', '>', now());

if ($status === 'scheduled') {
$query->where('date', 'invalid'); // intentionally trigger no results.
}
}
}

public function prepareForFakeQuery(): array
{
$data = parent::prepareForFakeQuery();
Expand Down
6 changes: 3 additions & 3 deletions src/Tags/Collection/Entries.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -184,7 +184,7 @@ protected function query()

$this->querySelect($query);
$this->querySite($query);
$this->queryStatus($query);
$this->queryPublished($query);
$this->queryPastFuture($query);
$this->querySinceUntil($query);
$this->queryTaxonomies($query);
Expand DownExpand Up@@ -270,13 +270,13 @@ protected function querySite($query)
return $query->where('site', $site);
}

protected function queryStatus($query)
protected function queryPublished($query)
{
if ($this->isQueryingCondition('status') || $this->isQueryingCondition('published')) {
return;
}

return $query->where('status', 'published');
return $query->where('published', true);
}

protected function queryPastFuture($query)
Expand Down
4 changes: 4 additions & 0 deletions src/Tags/Concerns/QueriesConditions.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -128,6 +128,10 @@ protected function queryCondition($query, $field, $condition, $value)

protected function queryIsCondition($query, $field, $value)
{
if ($field === 'status') {
return $query->whereStatus($value);
}

return $query->where($field, $value);
}

Expand Down
40 changes: 40 additions & 0 deletions tests/API/APITest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -99,6 +99,46 @@ public function it_filters_published_entries_by_default()
$this->assertEndpointNotFound('/api/collections/pages/entries/nectar');
}

/** @test */
public function it_filters_out_future_entries_from_future_private_collection()
{
Facades\Config::set('statamic.api.resources.collections', true);

Facades\Collection::make('test')->dated(true)
->pastDateBehavior('public')
->futureDateBehavior('private')
->save();

Facades\Entry::make()->collection('test')->id('a')->published(true)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('b')->published(false)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('c')->published(true)->date(now()->subDay())->save();
Facades\Entry::make()->collection('test')->id('d')->published(false)->date(now()->subDay())->save();

$response = $this->get('/api/collections/test/entries')->assertSuccessful();
$this->assertCount(1, $response->getData()->data);
$response->assertJsonPath('data.0.id', 'c');
}

/** @test */
public function it_filters_out_past_entries_from_past_private_collection()
{
Facades\Config::set('statamic.api.resources.collections', true);

Facades\Collection::make('test')->dated(true)
->pastDateBehavior('private')
->futureDateBehavior('public')
->save();

Facades\Entry::make()->collection('test')->id('a')->published(true)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('b')->published(false)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('c')->published(true)->date(now()->subDay())->save();
Facades\Entry::make()->collection('test')->id('d')->published(false)->date(now()->subDay())->save();

$response = $this->get('/api/collections/test/entries')->assertSuccessful();
$this->assertCount(1, $response->getData()->data);
$response->assertJsonPath('data.0.id', 'a');
}

/** @test */
public function it_can_filter_collection_entries_when_configuration_allows_for_it()
{
Expand Down
91 changes: 91 additions & 0 deletions tests/Data/Entries/EntryQueryBuilderTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -770,6 +770,97 @@ public function entries_are_found_using_lazy()
}

/** @test */
public function filtering_using_where_status_column_writes_deprecation_log()
{
$this->withoutDeprecationHandling();
$this->expectException(\ErrorException::class);
$this->expectExceptionMessage('Filtering by status is deprecated. Use whereStatus() instead.');

$this->createDummyCollectionAndEntries();

Entry::query()->where('collection', 'posts')->where('status', 'published')->get();
}

/** @test */
public function filtering_using_whereIn_status_column_writes_deprecation_log()
{
$this->withoutDeprecationHandling();
$this->expectException(\ErrorException::class);
$this->expectExceptionMessage('Filtering by status is deprecated. Use whereStatus() instead.');

$this->createDummyCollectionAndEntries();

Entry::query()->where('collection', 'posts')->whereIn('status', ['published'])->get();
}

/** @test */
public function filtering_by_unexpected_status_throws_exception()
{
$this->expectExceptionMessage('Invalid status [foo]');

Entry::query()->whereStatus('foo')->get();
}

/**
* @test
*
* @dataProvider filterByStatusProvider
*/
public function it_filters_by_status($status, $expected)
{
Collection::make('pages')->dated(false)->save();
EntryFactory::collection('pages')->id('page')->published(true)->create();
EntryFactory::collection('pages')->id('page-draft')->published(false)->create();

Collection::make('blog')->dated(true)->futureDateBehavior('private')->pastDateBehavior('public')->save();
EntryFactory::collection('blog')->id('blog-future')->published(true)->date(now()->addDay())->create();
EntryFactory::collection('blog')->id('blog-future-draft')->published(false)->date(now()->addDay())->create();
EntryFactory::collection('blog')->id('blog-past')->published(true)->date(now()->subDay())->create();
EntryFactory::collection('blog')->id('blog-past-draft')->published(false)->date(now()->subDay())->create();

Collection::make('events')->dated(true)->futureDateBehavior('public')->pastDateBehavior('private')->save();
EntryFactory::collection('events')->id('event-future')->published(true)->date(now()->addDay())->create();
EntryFactory::collection('events')->id('event-future-draft')->published(false)->date(now()->addDay())->create();
EntryFactory::collection('events')->id('event-past')->published(true)->date(now()->subDay())->create();
EntryFactory::collection('events')->id('event-past-draft')->published(false)->date(now()->subDay())->create();

Collection::make('calendar')->dated(true)->futureDateBehavior('public')->pastDateBehavior('public')->save();
EntryFactory::collection('calendar')->id('calendar-future')->published(true)->date(now()->addDay())->create();
EntryFactory::collection('calendar')->id('calendar-future-draft')->published(false)->date(now()->addDay())->create();
EntryFactory::collection('calendar')->id('calendar-past')->published(true)->date(now()->subDay())->create();
EntryFactory::collection('calendar')->id('calendar-past-draft')->published(false)->date(now()->subDay())->create();

$this->assertEquals($expected, Entry::query()->whereStatus($status)->get()->map->id->all());
}

public static function filterByStatusProvider()
{
return [
'draft' => ['draft', [
'page-draft',
'blog-future-draft',
'blog-past-draft',
'event-future-draft',
'event-past-draft',
'calendar-future-draft',
'calendar-past-draft',
]],
'published' => ['published', [
'page',
'blog-past',
'event-future',
'calendar-future',
'calendar-past',
]],
'scheduled' => ['scheduled', [
'blog-future',
]],
'expired' => ['expired', [
'event-past',
]],
];
}

public function values_can_be_plucked()
{
$this->createDummyCollectionAndEntries();
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' [5.x] Avoid querying status by jasonvarga · Pull Request #9317 · statamic/cms · GitHub
Skip to content
5 changes: 5 additions & 0 deletions src/Query/ItemQueryBuilder.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,4 +19,9 @@ protected function getBaseItems()
{
return $this->items;
}

public function whereStatus($status)
{
return $this->where('status', $status);
}
}
2 changes: 1 addition & 1 deletion src/Query/Scopes/Filters/Status.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,7 +26,7 @@ public function fieldItems()

public function apply($query, $values)
{
$query->where('status', $values['status']);
$query->whereStatus($values['status']);
}

public function badge($values)
Expand Down
4 changes: 2 additions & 2 deletions src/Query/StatusQueryBuilder.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,7 +36,7 @@ public function __construct(Builder $builder, $status = 'published')
public function get($columns = ['*'])
{
if ($this->queryFallbackStatus) {
$this->builder->where('status', $this->fallbackStatus);
$this->builder->whereStatus($this->fallbackStatus);
}

return $this->builder->get($columns);
Expand All@@ -49,7 +49,7 @@ public function first()

public function __call($method, $parameters)
{
if (in_array($method, self::METHODS) && in_array(Arr::first($parameters), ['status', 'published'])) {
if ((in_array($method, self::METHODS) && in_array(Arr::first($parameters), ['status', 'published'])) || $method === 'whereStatus') {
$this->queryFallbackStatus = false;
}

Expand Down
76 changes: 75 additions & 1 deletion src/Stache/Query/EntryQueryBuilder.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,13 +5,16 @@
use Statamic\Contracts\Entries\QueryBuilder;
use Statamic\Entries\EntryCollection;
use Statamic\Facades;
use Statamic\Facades\Collection;
use Statamic\Support\Arr;

class EntryQueryBuilder extends Builder implements QueryBuilder
{
use QueriesTaxonomizedEntries;

protected $collections;
private const STATUSES = ['published', 'draft', 'scheduled', 'expired'];

protected $collections = [];

public function where($column, $operator = null, $value = null, $boolean = 'and')
{
Expand All@@ -21,6 +24,10 @@ public function where($column, $operator = null, $value = null, $boolean = 'and'
return $this;
}

if ($column === 'status') {
trigger_error('Filtering by status is deprecated. Use whereStatus() instead.', E_USER_DEPRECATED);
}

return parent::where($column, $operator, $value, $boolean);
}

Expand All@@ -32,6 +39,10 @@ public function whereIn($column, $values, $boolean = 'and')
return $this;
}

if ($column === 'status') {
trigger_error('Filtering by status is deprecated. Use whereStatus() instead.', E_USER_DEPRECATED);
}

return parent::whereIn($column, $values, $boolean);
}

Expand DownExpand Up@@ -133,6 +144,69 @@ protected function getWhereColumnKeyValuesByIndex($column)
});
}

public function whereStatus(string $status)
{
if (! in_array($status, self::STATUSES)) {
throw new \Exception("Invalid status [$status]");
}

if ($status === 'draft') {
return $this->where('published', false);
}

$this->where('published', true);

return $this->where(fn ($query) => $this
->getCollectionsForStatus()
->each(fn ($collection) => $query->orWhere(fn ($q) => $this->addCollectionStatusLogicToQuery($q, $status, $collection))));
}

private function getCollectionsForStatus()
{
// Since we have to add nested queries for each collection, if collections have been provided,
// we'll use those to avoid the need for adding unnecessary query clauses.

if (empty($this->collections)) {
return Collection::all();
}

return collect($this->collections)->map(fn ($handle) => Collection::find($handle));
}

private function addCollectionStatusLogicToQuery($query, $status, $collection)
{
// Using collectionHandle instead of collection because we intercept collection
// and put it on a property. In this case we actually want the indexed value.
// We can probably refactor this elsewhere later.
$query->where('collectionHandle', $collection->handle());

if ($collection->futureDateBehavior() === 'public' && $collection->pastDateBehavior() === 'public') {
if ($status === 'scheduled' || $status === 'expired') {
$query->where('date', 'invalid'); // intentionally trigger no results.
}
}

if ($collection->futureDateBehavior() === 'private') {
$status === 'scheduled'
? $query->where('date', '>', now())
: $query->where('date', '<', now());

if ($status === 'expired') {
$query->where('date', 'invalid'); // intentionally trigger no results.
}
}

if ($collection->pastDateBehavior() === 'private') {
$status === 'expired'
? $query->where('date', '<', now())
: $query->where('date', '>', now());

if ($status === 'scheduled') {
$query->where('date', 'invalid'); // intentionally trigger no results.
}
}
}

public function prepareForFakeQuery(): array
{
$data = parent::prepareForFakeQuery();
Expand Down
6 changes: 3 additions & 3 deletions src/Tags/Collection/Entries.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -184,7 +184,7 @@ protected function query()

$this->querySelect($query);
$this->querySite($query);
$this->queryStatus($query);
$this->queryPublished($query);
$this->queryPastFuture($query);
$this->querySinceUntil($query);
$this->queryTaxonomies($query);
Expand DownExpand Up@@ -270,13 +270,13 @@ protected function querySite($query)
return $query->where('site', $site);
}

protected function queryStatus($query)
protected function queryPublished($query)
{
if ($this->isQueryingCondition('status') || $this->isQueryingCondition('published')) {
return;
}

return $query->where('status', 'published');
return $query->where('published', true);
}

protected function queryPastFuture($query)
Expand Down
4 changes: 4 additions & 0 deletions src/Tags/Concerns/QueriesConditions.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -128,6 +128,10 @@ protected function queryCondition($query, $field, $condition, $value)

protected function queryIsCondition($query, $field, $value)
{
if ($field === 'status') {
return $query->whereStatus($value);
}

return $query->where($field, $value);
}

Expand Down
40 changes: 40 additions & 0 deletions tests/API/APITest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -99,6 +99,46 @@ public function it_filters_published_entries_by_default()
$this->assertEndpointNotFound('/api/collections/pages/entries/nectar');
}

/** @test */
public function it_filters_out_future_entries_from_future_private_collection()
{
Facades\Config::set('statamic.api.resources.collections', true);

Facades\Collection::make('test')->dated(true)
->pastDateBehavior('public')
->futureDateBehavior('private')
->save();

Facades\Entry::make()->collection('test')->id('a')->published(true)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('b')->published(false)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('c')->published(true)->date(now()->subDay())->save();
Facades\Entry::make()->collection('test')->id('d')->published(false)->date(now()->subDay())->save();

$response = $this->get('/api/collections/test/entries')->assertSuccessful();
$this->assertCount(1, $response->getData()->data);
$response->assertJsonPath('data.0.id', 'c');
}

/** @test */
public function it_filters_out_past_entries_from_past_private_collection()
{
Facades\Config::set('statamic.api.resources.collections', true);

Facades\Collection::make('test')->dated(true)
->pastDateBehavior('private')
->futureDateBehavior('public')
->save();

Facades\Entry::make()->collection('test')->id('a')->published(true)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('b')->published(false)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('c')->published(true)->date(now()->subDay())->save();
Facades\Entry::make()->collection('test')->id('d')->published(false)->date(now()->subDay())->save();

$response = $this->get('/api/collections/test/entries')->assertSuccessful();
$this->assertCount(1, $response->getData()->data);
$response->assertJsonPath('data.0.id', 'a');
}

/** @test */
public function it_can_filter_collection_entries_when_configuration_allows_for_it()
{
Expand Down
91 changes: 91 additions & 0 deletions tests/Data/Entries/EntryQueryBuilderTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -770,6 +770,97 @@ public function entries_are_found_using_lazy()
}

/** @test */
public function filtering_using_where_status_column_writes_deprecation_log()
{
$this->withoutDeprecationHandling();
$this->expectException(\ErrorException::class);
$this->expectExceptionMessage('Filtering by status is deprecated. Use whereStatus() instead.');

$this->createDummyCollectionAndEntries();

Entry::query()->where('collection', 'posts')->where('status', 'published')->get();
}

/** @test */
public function filtering_using_whereIn_status_column_writes_deprecation_log()
{
$this->withoutDeprecationHandling();
$this->expectException(\ErrorException::class);
$this->expectExceptionMessage('Filtering by status is deprecated. Use whereStatus() instead.');

$this->createDummyCollectionAndEntries();

Entry::query()->where('collection', 'posts')->whereIn('status', ['published'])->get();
}

/** @test */
public function filtering_by_unexpected_status_throws_exception()
{
$this->expectExceptionMessage('Invalid status [foo]');

Entry::query()->whereStatus('foo')->get();
}

/**
* @test
*
* @dataProvider filterByStatusProvider
*/
public function it_filters_by_status($status, $expected)
{
Collection::make('pages')->dated(false)->save();
EntryFactory::collection('pages')->id('page')->published(true)->create();
EntryFactory::collection('pages')->id('page-draft')->published(false)->create();

Collection::make('blog')->dated(true)->futureDateBehavior('private')->pastDateBehavior('public')->save();
EntryFactory::collection('blog')->id('blog-future')->published(true)->date(now()->addDay())->create();
EntryFactory::collection('blog')->id('blog-future-draft')->published(false)->date(now()->addDay())->create();
EntryFactory::collection('blog')->id('blog-past')->published(true)->date(now()->subDay())->create();
EntryFactory::collection('blog')->id('blog-past-draft')->published(false)->date(now()->subDay())->create();

Collection::make('events')->dated(true)->futureDateBehavior('public')->pastDateBehavior('private')->save();
EntryFactory::collection('events')->id('event-future')->published(true)->date(now()->addDay())->create();
EntryFactory::collection('events')->id('event-future-draft')->published(false)->date(now()->addDay())->create();
EntryFactory::collection('events')->id('event-past')->published(true)->date(now()->subDay())->create();
EntryFactory::collection('events')->id('event-past-draft')->published(false)->date(now()->subDay())->create();

Collection::make('calendar')->dated(true)->futureDateBehavior('public')->pastDateBehavior('public')->save();
EntryFactory::collection('calendar')->id('calendar-future')->published(true)->date(now()->addDay())->create();
EntryFactory::collection('calendar')->id('calendar-future-draft')->published(false)->date(now()->addDay())->create();
EntryFactory::collection('calendar')->id('calendar-past')->published(true)->date(now()->subDay())->create();
EntryFactory::collection('calendar')->id('calendar-past-draft')->published(false)->date(now()->subDay())->create();

$this->assertEquals($expected, Entry::query()->whereStatus($status)->get()->map->id->all());
}

public static function filterByStatusProvider()
{
return [
'draft' => ['draft', [
'page-draft',
'blog-future-draft',
'blog-past-draft',
'event-future-draft',
'event-past-draft',
'calendar-future-draft',
'calendar-past-draft',
]],
'published' => ['published', [
'page',
'blog-past',
'event-future',
'calendar-future',
'calendar-past',
]],
'scheduled' => ['scheduled', [
'blog-future',
]],
'expired' => ['expired', [
'event-past',
]],
];
}

public function values_can_be_plucked()
{
$this->createDummyCollectionAndEntries();
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [5.x] Avoid querying status by jasonvarga · Pull Request #9317 · statamic/cms · GitHub
Skip to content
5 changes: 5 additions & 0 deletions src/Query/ItemQueryBuilder.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,4 +19,9 @@ protected function getBaseItems()
{
return $this->items;
}

public function whereStatus($status)
{
return $this->where('status', $status);
}
}
2 changes: 1 addition & 1 deletion src/Query/Scopes/Filters/Status.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,7 +26,7 @@ public function fieldItems()

public function apply($query, $values)
{
$query->where('status', $values['status']);
$query->whereStatus($values['status']);
}

public function badge($values)
Expand Down
4 changes: 2 additions & 2 deletions src/Query/StatusQueryBuilder.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,7 +36,7 @@ public function __construct(Builder $builder, $status = 'published')
public function get($columns = ['*'])
{
if ($this->queryFallbackStatus) {
$this->builder->where('status', $this->fallbackStatus);
$this->builder->whereStatus($this->fallbackStatus);
}

return $this->builder->get($columns);
Expand All@@ -49,7 +49,7 @@ public function first()

public function __call($method, $parameters)
{
if (in_array($method, self::METHODS) && in_array(Arr::first($parameters), ['status', 'published'])) {
if ((in_array($method, self::METHODS) && in_array(Arr::first($parameters), ['status', 'published'])) || $method === 'whereStatus') {
$this->queryFallbackStatus = false;
}

Expand Down
76 changes: 75 additions & 1 deletion src/Stache/Query/EntryQueryBuilder.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,13 +5,16 @@
use Statamic\Contracts\Entries\QueryBuilder;
use Statamic\Entries\EntryCollection;
use Statamic\Facades;
use Statamic\Facades\Collection;
use Statamic\Support\Arr;

class EntryQueryBuilder extends Builder implements QueryBuilder
{
use QueriesTaxonomizedEntries;

protected $collections;
private const STATUSES = ['published', 'draft', 'scheduled', 'expired'];

protected $collections = [];

public function where($column, $operator = null, $value = null, $boolean = 'and')
{
Expand All@@ -21,6 +24,10 @@ public function where($column, $operator = null, $value = null, $boolean = 'and'
return $this;
}

if ($column === 'status') {
trigger_error('Filtering by status is deprecated. Use whereStatus() instead.', E_USER_DEPRECATED);
}

return parent::where($column, $operator, $value, $boolean);
}

Expand All@@ -32,6 +39,10 @@ public function whereIn($column, $values, $boolean = 'and')
return $this;
}

if ($column === 'status') {
trigger_error('Filtering by status is deprecated. Use whereStatus() instead.', E_USER_DEPRECATED);
}

return parent::whereIn($column, $values, $boolean);
}

Expand DownExpand Up@@ -133,6 +144,69 @@ protected function getWhereColumnKeyValuesByIndex($column)
});
}

public function whereStatus(string $status)
{
if (! in_array($status, self::STATUSES)) {
throw new \Exception("Invalid status [$status]");
}

if ($status === 'draft') {
return $this->where('published', false);
}

$this->where('published', true);

return $this->where(fn ($query) => $this
->getCollectionsForStatus()
->each(fn ($collection) => $query->orWhere(fn ($q) => $this->addCollectionStatusLogicToQuery($q, $status, $collection))));
}

private function getCollectionsForStatus()
{
// Since we have to add nested queries for each collection, if collections have been provided,
// we'll use those to avoid the need for adding unnecessary query clauses.

if (empty($this->collections)) {
return Collection::all();
}

return collect($this->collections)->map(fn ($handle) => Collection::find($handle));
}

private function addCollectionStatusLogicToQuery($query, $status, $collection)
{
// Using collectionHandle instead of collection because we intercept collection
// and put it on a property. In this case we actually want the indexed value.
// We can probably refactor this elsewhere later.
$query->where('collectionHandle', $collection->handle());

if ($collection->futureDateBehavior() === 'public' && $collection->pastDateBehavior() === 'public') {
if ($status === 'scheduled' || $status === 'expired') {
$query->where('date', 'invalid'); // intentionally trigger no results.
}
}

if ($collection->futureDateBehavior() === 'private') {
$status === 'scheduled'
? $query->where('date', '>', now())
: $query->where('date', '<', now());

if ($status === 'expired') {
$query->where('date', 'invalid'); // intentionally trigger no results.
}
}

if ($collection->pastDateBehavior() === 'private') {
$status === 'expired'
? $query->where('date', '<', now())
: $query->where('date', '>', now());

if ($status === 'scheduled') {
$query->where('date', 'invalid'); // intentionally trigger no results.
}
}
}

public function prepareForFakeQuery(): array
{
$data = parent::prepareForFakeQuery();
Expand Down
6 changes: 3 additions & 3 deletions src/Tags/Collection/Entries.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -184,7 +184,7 @@ protected function query()

$this->querySelect($query);
$this->querySite($query);
$this->queryStatus($query);
$this->queryPublished($query);
$this->queryPastFuture($query);
$this->querySinceUntil($query);
$this->queryTaxonomies($query);
Expand DownExpand Up@@ -270,13 +270,13 @@ protected function querySite($query)
return $query->where('site', $site);
}

protected function queryStatus($query)
protected function queryPublished($query)
{
if ($this->isQueryingCondition('status') || $this->isQueryingCondition('published')) {
return;
}

return $query->where('status', 'published');
return $query->where('published', true);
}

protected function queryPastFuture($query)
Expand Down
4 changes: 4 additions & 0 deletions src/Tags/Concerns/QueriesConditions.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -128,6 +128,10 @@ protected function queryCondition($query, $field, $condition, $value)

protected function queryIsCondition($query, $field, $value)
{
if ($field === 'status') {
return $query->whereStatus($value);
}

return $query->where($field, $value);
}

Expand Down
40 changes: 40 additions & 0 deletions tests/API/APITest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -99,6 +99,46 @@ public function it_filters_published_entries_by_default()
$this->assertEndpointNotFound('/api/collections/pages/entries/nectar');
}

/** @test */
public function it_filters_out_future_entries_from_future_private_collection()
{
Facades\Config::set('statamic.api.resources.collections', true);

Facades\Collection::make('test')->dated(true)
->pastDateBehavior('public')
->futureDateBehavior('private')
->save();

Facades\Entry::make()->collection('test')->id('a')->published(true)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('b')->published(false)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('c')->published(true)->date(now()->subDay())->save();
Facades\Entry::make()->collection('test')->id('d')->published(false)->date(now()->subDay())->save();

$response = $this->get('/api/collections/test/entries')->assertSuccessful();
$this->assertCount(1, $response->getData()->data);
$response->assertJsonPath('data.0.id', 'c');
}

/** @test */
public function it_filters_out_past_entries_from_past_private_collection()
{
Facades\Config::set('statamic.api.resources.collections', true);

Facades\Collection::make('test')->dated(true)
->pastDateBehavior('private')
->futureDateBehavior('public')
->save();

Facades\Entry::make()->collection('test')->id('a')->published(true)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('b')->published(false)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('c')->published(true)->date(now()->subDay())->save();
Facades\Entry::make()->collection('test')->id('d')->published(false)->date(now()->subDay())->save();

$response = $this->get('/api/collections/test/entries')->assertSuccessful();
$this->assertCount(1, $response->getData()->data);
$response->assertJsonPath('data.0.id', 'a');
}

/** @test */
public function it_can_filter_collection_entries_when_configuration_allows_for_it()
{
Expand Down
91 changes: 91 additions & 0 deletions tests/Data/Entries/EntryQueryBuilderTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -770,6 +770,97 @@ public function entries_are_found_using_lazy()
}

/** @test */
public function filtering_using_where_status_column_writes_deprecation_log()
{
$this->withoutDeprecationHandling();
$this->expectException(\ErrorException::class);
$this->expectExceptionMessage('Filtering by status is deprecated. Use whereStatus() instead.');

$this->createDummyCollectionAndEntries();

Entry::query()->where('collection', 'posts')->where('status', 'published')->get();
}

/** @test */
public function filtering_using_whereIn_status_column_writes_deprecation_log()
{
$this->withoutDeprecationHandling();
$this->expectException(\ErrorException::class);
$this->expectExceptionMessage('Filtering by status is deprecated. Use whereStatus() instead.');

$this->createDummyCollectionAndEntries();

Entry::query()->where('collection', 'posts')->whereIn('status', ['published'])->get();
}

/** @test */
public function filtering_by_unexpected_status_throws_exception()
{
$this->expectExceptionMessage('Invalid status [foo]');

Entry::query()->whereStatus('foo')->get();
}

/**
* @test
*
* @dataProvider filterByStatusProvider
*/
public function it_filters_by_status($status, $expected)
{
Collection::make('pages')->dated(false)->save();
EntryFactory::collection('pages')->id('page')->published(true)->create();
EntryFactory::collection('pages')->id('page-draft')->published(false)->create();

Collection::make('blog')->dated(true)->futureDateBehavior('private')->pastDateBehavior('public')->save();
EntryFactory::collection('blog')->id('blog-future')->published(true)->date(now()->addDay())->create();
EntryFactory::collection('blog')->id('blog-future-draft')->published(false)->date(now()->addDay())->create();
EntryFactory::collection('blog')->id('blog-past')->published(true)->date(now()->subDay())->create();
EntryFactory::collection('blog')->id('blog-past-draft')->published(false)->date(now()->subDay())->create();

Collection::make('events')->dated(true)->futureDateBehavior('public')->pastDateBehavior('private')->save();
EntryFactory::collection('events')->id('event-future')->published(true)->date(now()->addDay())->create();
EntryFactory::collection('events')->id('event-future-draft')->published(false)->date(now()->addDay())->create();
EntryFactory::collection('events')->id('event-past')->published(true)->date(now()->subDay())->create();
EntryFactory::collection('events')->id('event-past-draft')->published(false)->date(now()->subDay())->create();

Collection::make('calendar')->dated(true)->futureDateBehavior('public')->pastDateBehavior('public')->save();
EntryFactory::collection('calendar')->id('calendar-future')->published(true)->date(now()->addDay())->create();
EntryFactory::collection('calendar')->id('calendar-future-draft')->published(false)->date(now()->addDay())->create();
EntryFactory::collection('calendar')->id('calendar-past')->published(true)->date(now()->subDay())->create();
EntryFactory::collection('calendar')->id('calendar-past-draft')->published(false)->date(now()->subDay())->create();

$this->assertEquals($expected, Entry::query()->whereStatus($status)->get()->map->id->all());
}

public static function filterByStatusProvider()
{
return [
'draft' => ['draft', [
'page-draft',
'blog-future-draft',
'blog-past-draft',
'event-future-draft',
'event-past-draft',
'calendar-future-draft',
'calendar-past-draft',
]],
'published' => ['published', [
'page',
'blog-past',
'event-future',
'calendar-future',
'calendar-past',
]],
'scheduled' => ['scheduled', [
'blog-future',
]],
'expired' => ['expired', [
'event-past',
]],
];
}

public function values_can_be_plucked()
{
$this->createDummyCollectionAndEntries();
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [5.x] Avoid querying status by jasonvarga · Pull Request #9317 · statamic/cms · GitHub
Skip to content
5 changes: 5 additions & 0 deletions src/Query/ItemQueryBuilder.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,4 +19,9 @@ protected function getBaseItems()
{
return $this->items;
}

public function whereStatus($status)
{
return $this->where('status', $status);
}
}
2 changes: 1 addition & 1 deletion src/Query/Scopes/Filters/Status.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,7 +26,7 @@ public function fieldItems()

public function apply($query, $values)
{
$query->where('status', $values['status']);
$query->whereStatus($values['status']);
}

public function badge($values)
Expand Down
4 changes: 2 additions & 2 deletions src/Query/StatusQueryBuilder.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,7 +36,7 @@ public function __construct(Builder $builder, $status = 'published')
public function get($columns = ['*'])
{
if ($this->queryFallbackStatus) {
$this->builder->where('status', $this->fallbackStatus);
$this->builder->whereStatus($this->fallbackStatus);
}

return $this->builder->get($columns);
Expand All@@ -49,7 +49,7 @@ public function first()

public function __call($method, $parameters)
{
if (in_array($method, self::METHODS) && in_array(Arr::first($parameters), ['status', 'published'])) {
if ((in_array($method, self::METHODS) && in_array(Arr::first($parameters), ['status', 'published'])) || $method === 'whereStatus') {
$this->queryFallbackStatus = false;
}

Expand Down
76 changes: 75 additions & 1 deletion src/Stache/Query/EntryQueryBuilder.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,13 +5,16 @@
use Statamic\Contracts\Entries\QueryBuilder;
use Statamic\Entries\EntryCollection;
use Statamic\Facades;
use Statamic\Facades\Collection;
use Statamic\Support\Arr;

class EntryQueryBuilder extends Builder implements QueryBuilder
{
use QueriesTaxonomizedEntries;

protected $collections;
private const STATUSES = ['published', 'draft', 'scheduled', 'expired'];

protected $collections = [];

public function where($column, $operator = null, $value = null, $boolean = 'and')
{
Expand All@@ -21,6 +24,10 @@ public function where($column, $operator = null, $value = null, $boolean = 'and'
return $this;
}

if ($column === 'status') {
trigger_error('Filtering by status is deprecated. Use whereStatus() instead.', E_USER_DEPRECATED);
}

return parent::where($column, $operator, $value, $boolean);
}

Expand All@@ -32,6 +39,10 @@ public function whereIn($column, $values, $boolean = 'and')
return $this;
}

if ($column === 'status') {
trigger_error('Filtering by status is deprecated. Use whereStatus() instead.', E_USER_DEPRECATED);
}

return parent::whereIn($column, $values, $boolean);
}

Expand DownExpand Up@@ -133,6 +144,69 @@ protected function getWhereColumnKeyValuesByIndex($column)
});
}

public function whereStatus(string $status)
{
if (! in_array($status, self::STATUSES)) {
throw new \Exception("Invalid status [$status]");
}

if ($status === 'draft') {
return $this->where('published', false);
}

$this->where('published', true);

return $this->where(fn ($query) => $this
->getCollectionsForStatus()
->each(fn ($collection) => $query->orWhere(fn ($q) => $this->addCollectionStatusLogicToQuery($q, $status, $collection))));
}

private function getCollectionsForStatus()
{
// Since we have to add nested queries for each collection, if collections have been provided,
// we'll use those to avoid the need for adding unnecessary query clauses.

if (empty($this->collections)) {
return Collection::all();
}

return collect($this->collections)->map(fn ($handle) => Collection::find($handle));
}

private function addCollectionStatusLogicToQuery($query, $status, $collection)
{
// Using collectionHandle instead of collection because we intercept collection
// and put it on a property. In this case we actually want the indexed value.
// We can probably refactor this elsewhere later.
$query->where('collectionHandle', $collection->handle());

if ($collection->futureDateBehavior() === 'public' && $collection->pastDateBehavior() === 'public') {
if ($status === 'scheduled' || $status === 'expired') {
$query->where('date', 'invalid'); // intentionally trigger no results.
}
}

if ($collection->futureDateBehavior() === 'private') {
$status === 'scheduled'
? $query->where('date', '>', now())
: $query->where('date', '<', now());

if ($status === 'expired') {
$query->where('date', 'invalid'); // intentionally trigger no results.
}
}

if ($collection->pastDateBehavior() === 'private') {
$status === 'expired'
? $query->where('date', '<', now())
: $query->where('date', '>', now());

if ($status === 'scheduled') {
$query->where('date', 'invalid'); // intentionally trigger no results.
}
}
}

public function prepareForFakeQuery(): array
{
$data = parent::prepareForFakeQuery();
Expand Down
6 changes: 3 additions & 3 deletions src/Tags/Collection/Entries.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -184,7 +184,7 @@ protected function query()

$this->querySelect($query);
$this->querySite($query);
$this->queryStatus($query);
$this->queryPublished($query);
$this->queryPastFuture($query);
$this->querySinceUntil($query);
$this->queryTaxonomies($query);
Expand DownExpand Up@@ -270,13 +270,13 @@ protected function querySite($query)
return $query->where('site', $site);
}

protected function queryStatus($query)
protected function queryPublished($query)
{
if ($this->isQueryingCondition('status') || $this->isQueryingCondition('published')) {
return;
}

return $query->where('status', 'published');
return $query->where('published', true);
}

protected function queryPastFuture($query)
Expand Down
4 changes: 4 additions & 0 deletions src/Tags/Concerns/QueriesConditions.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -128,6 +128,10 @@ protected function queryCondition($query, $field, $condition, $value)

protected function queryIsCondition($query, $field, $value)
{
if ($field === 'status') {
return $query->whereStatus($value);
}

return $query->where($field, $value);
}

Expand Down
40 changes: 40 additions & 0 deletions tests/API/APITest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -99,6 +99,46 @@ public function it_filters_published_entries_by_default()
$this->assertEndpointNotFound('/api/collections/pages/entries/nectar');
}

/** @test */
public function it_filters_out_future_entries_from_future_private_collection()
{
Facades\Config::set('statamic.api.resources.collections', true);

Facades\Collection::make('test')->dated(true)
->pastDateBehavior('public')
->futureDateBehavior('private')
->save();

Facades\Entry::make()->collection('test')->id('a')->published(true)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('b')->published(false)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('c')->published(true)->date(now()->subDay())->save();
Facades\Entry::make()->collection('test')->id('d')->published(false)->date(now()->subDay())->save();

$response = $this->get('/api/collections/test/entries')->assertSuccessful();
$this->assertCount(1, $response->getData()->data);
$response->assertJsonPath('data.0.id', 'c');
}

/** @test */
public function it_filters_out_past_entries_from_past_private_collection()
{
Facades\Config::set('statamic.api.resources.collections', true);

Facades\Collection::make('test')->dated(true)
->pastDateBehavior('private')
->futureDateBehavior('public')
->save();

Facades\Entry::make()->collection('test')->id('a')->published(true)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('b')->published(false)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('c')->published(true)->date(now()->subDay())->save();
Facades\Entry::make()->collection('test')->id('d')->published(false)->date(now()->subDay())->save();

$response = $this->get('/api/collections/test/entries')->assertSuccessful();
$this->assertCount(1, $response->getData()->data);
$response->assertJsonPath('data.0.id', 'a');
}

/** @test */
public function it_can_filter_collection_entries_when_configuration_allows_for_it()
{
Expand Down
91 changes: 91 additions & 0 deletions tests/Data/Entries/EntryQueryBuilderTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -770,6 +770,97 @@ public function entries_are_found_using_lazy()
}

/** @test */
public function filtering_using_where_status_column_writes_deprecation_log()
{
$this->withoutDeprecationHandling();
$this->expectException(\ErrorException::class);
$this->expectExceptionMessage('Filtering by status is deprecated. Use whereStatus() instead.');

$this->createDummyCollectionAndEntries();

Entry::query()->where('collection', 'posts')->where('status', 'published')->get();
}

/** @test */
public function filtering_using_whereIn_status_column_writes_deprecation_log()
{
$this->withoutDeprecationHandling();
$this->expectException(\ErrorException::class);
$this->expectExceptionMessage('Filtering by status is deprecated. Use whereStatus() instead.');

$this->createDummyCollectionAndEntries();

Entry::query()->where('collection', 'posts')->whereIn('status', ['published'])->get();
}

/** @test */
public function filtering_by_unexpected_status_throws_exception()
{
$this->expectExceptionMessage('Invalid status [foo]');

Entry::query()->whereStatus('foo')->get();
}

/**
* @test
*
* @dataProvider filterByStatusProvider
*/
public function it_filters_by_status($status, $expected)
{
Collection::make('pages')->dated(false)->save();
EntryFactory::collection('pages')->id('page')->published(true)->create();
EntryFactory::collection('pages')->id('page-draft')->published(false)->create();

Collection::make('blog')->dated(true)->futureDateBehavior('private')->pastDateBehavior('public')->save();
EntryFactory::collection('blog')->id('blog-future')->published(true)->date(now()->addDay())->create();
EntryFactory::collection('blog')->id('blog-future-draft')->published(false)->date(now()->addDay())->create();
EntryFactory::collection('blog')->id('blog-past')->published(true)->date(now()->subDay())->create();
EntryFactory::collection('blog')->id('blog-past-draft')->published(false)->date(now()->subDay())->create();

Collection::make('events')->dated(true)->futureDateBehavior('public')->pastDateBehavior('private')->save();
EntryFactory::collection('events')->id('event-future')->published(true)->date(now()->addDay())->create();
EntryFactory::collection('events')->id('event-future-draft')->published(false)->date(now()->addDay())->create();
EntryFactory::collection('events')->id('event-past')->published(true)->date(now()->subDay())->create();
EntryFactory::collection('events')->id('event-past-draft')->published(false)->date(now()->subDay())->create();

Collection::make('calendar')->dated(true)->futureDateBehavior('public')->pastDateBehavior('public')->save();
EntryFactory::collection('calendar')->id('calendar-future')->published(true)->date(now()->addDay())->create();
EntryFactory::collection('calendar')->id('calendar-future-draft')->published(false)->date(now()->addDay())->create();
EntryFactory::collection('calendar')->id('calendar-past')->published(true)->date(now()->subDay())->create();
EntryFactory::collection('calendar')->id('calendar-past-draft')->published(false)->date(now()->subDay())->create();

$this->assertEquals($expected, Entry::query()->whereStatus($status)->get()->map->id->all());
}

public static function filterByStatusProvider()
{
return [
'draft' => ['draft', [
'page-draft',
'blog-future-draft',
'blog-past-draft',
'event-future-draft',
'event-past-draft',
'calendar-future-draft',
'calendar-past-draft',
]],
'published' => ['published', [
'page',
'blog-past',
'event-future',
'calendar-future',
'calendar-past',
]],
'scheduled' => ['scheduled', [
'blog-future',
]],
'expired' => ['expired', [
'event-past',
]],
];
}

public function values_can_be_plucked()
{
$this->createDummyCollectionAndEntries();
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); [5.x] Avoid querying status by jasonvarga · Pull Request #9317 · statamic/cms · GitHub
Skip to content
5 changes: 5 additions & 0 deletions src/Query/ItemQueryBuilder.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,4 +19,9 @@ protected function getBaseItems()
{
return $this->items;
}

public function whereStatus($status)
{
return $this->where('status', $status);
}
}
2 changes: 1 addition & 1 deletion src/Query/Scopes/Filters/Status.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,7 +26,7 @@ public function fieldItems()

public function apply($query, $values)
{
$query->where('status', $values['status']);
$query->whereStatus($values['status']);
}

public function badge($values)
Expand Down
4 changes: 2 additions & 2 deletions src/Query/StatusQueryBuilder.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,7 +36,7 @@ public function __construct(Builder $builder, $status = 'published')
public function get($columns = ['*'])
{
if ($this->queryFallbackStatus) {
$this->builder->where('status', $this->fallbackStatus);
$this->builder->whereStatus($this->fallbackStatus);
}

return $this->builder->get($columns);
Expand All@@ -49,7 +49,7 @@ public function first()

public function __call($method, $parameters)
{
if (in_array($method, self::METHODS) && in_array(Arr::first($parameters), ['status', 'published'])) {
if ((in_array($method, self::METHODS) && in_array(Arr::first($parameters), ['status', 'published'])) || $method === 'whereStatus') {
$this->queryFallbackStatus = false;
}

Expand Down
76 changes: 75 additions & 1 deletion src/Stache/Query/EntryQueryBuilder.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,13 +5,16 @@
use Statamic\Contracts\Entries\QueryBuilder;
use Statamic\Entries\EntryCollection;
use Statamic\Facades;
use Statamic\Facades\Collection;
use Statamic\Support\Arr;

class EntryQueryBuilder extends Builder implements QueryBuilder
{
use QueriesTaxonomizedEntries;

protected $collections;
private const STATUSES = ['published', 'draft', 'scheduled', 'expired'];

protected $collections = [];

public function where($column, $operator = null, $value = null, $boolean = 'and')
{
Expand All@@ -21,6 +24,10 @@ public function where($column, $operator = null, $value = null, $boolean = 'and'
return $this;
}

if ($column === 'status') {
trigger_error('Filtering by status is deprecated. Use whereStatus() instead.', E_USER_DEPRECATED);
}

return parent::where($column, $operator, $value, $boolean);
}

Expand All@@ -32,6 +39,10 @@ public function whereIn($column, $values, $boolean = 'and')
return $this;
}

if ($column === 'status') {
trigger_error('Filtering by status is deprecated. Use whereStatus() instead.', E_USER_DEPRECATED);
}

return parent::whereIn($column, $values, $boolean);
}

Expand DownExpand Up@@ -133,6 +144,69 @@ protected function getWhereColumnKeyValuesByIndex($column)
});
}

public function whereStatus(string $status)
{
if (! in_array($status, self::STATUSES)) {
throw new \Exception("Invalid status [$status]");
}

if ($status === 'draft') {
return $this->where('published', false);
}

$this->where('published', true);

return $this->where(fn ($query) => $this
->getCollectionsForStatus()
->each(fn ($collection) => $query->orWhere(fn ($q) => $this->addCollectionStatusLogicToQuery($q, $status, $collection))));
}

private function getCollectionsForStatus()
{
// Since we have to add nested queries for each collection, if collections have been provided,
// we'll use those to avoid the need for adding unnecessary query clauses.

if (empty($this->collections)) {
return Collection::all();
}

return collect($this->collections)->map(fn ($handle) => Collection::find($handle));
}

private function addCollectionStatusLogicToQuery($query, $status, $collection)
{
// Using collectionHandle instead of collection because we intercept collection
// and put it on a property. In this case we actually want the indexed value.
// We can probably refactor this elsewhere later.
$query->where('collectionHandle', $collection->handle());

if ($collection->futureDateBehavior() === 'public' && $collection->pastDateBehavior() === 'public') {
if ($status === 'scheduled' || $status === 'expired') {
$query->where('date', 'invalid'); // intentionally trigger no results.
}
}

if ($collection->futureDateBehavior() === 'private') {
$status === 'scheduled'
? $query->where('date', '>', now())
: $query->where('date', '<', now());

if ($status === 'expired') {
$query->where('date', 'invalid'); // intentionally trigger no results.
}
}

if ($collection->pastDateBehavior() === 'private') {
$status === 'expired'
? $query->where('date', '<', now())
: $query->where('date', '>', now());

if ($status === 'scheduled') {
$query->where('date', 'invalid'); // intentionally trigger no results.
}
}
}

public function prepareForFakeQuery(): array
{
$data = parent::prepareForFakeQuery();
Expand Down
6 changes: 3 additions & 3 deletions src/Tags/Collection/Entries.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -184,7 +184,7 @@ protected function query()

$this->querySelect($query);
$this->querySite($query);
$this->queryStatus($query);
$this->queryPublished($query);
$this->queryPastFuture($query);
$this->querySinceUntil($query);
$this->queryTaxonomies($query);
Expand DownExpand Up@@ -270,13 +270,13 @@ protected function querySite($query)
return $query->where('site', $site);
}

protected function queryStatus($query)
protected function queryPublished($query)
{
if ($this->isQueryingCondition('status') || $this->isQueryingCondition('published')) {
return;
}

return $query->where('status', 'published');
return $query->where('published', true);
}

protected function queryPastFuture($query)
Expand Down
4 changes: 4 additions & 0 deletions src/Tags/Concerns/QueriesConditions.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -128,6 +128,10 @@ protected function queryCondition($query, $field, $condition, $value)

protected function queryIsCondition($query, $field, $value)
{
if ($field === 'status') {
return $query->whereStatus($value);
}

return $query->where($field, $value);
}

Expand Down
40 changes: 40 additions & 0 deletions tests/API/APITest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -99,6 +99,46 @@ public function it_filters_published_entries_by_default()
$this->assertEndpointNotFound('/api/collections/pages/entries/nectar');
}

/** @test */
public function it_filters_out_future_entries_from_future_private_collection()
{
Facades\Config::set('statamic.api.resources.collections', true);

Facades\Collection::make('test')->dated(true)
->pastDateBehavior('public')
->futureDateBehavior('private')
->save();

Facades\Entry::make()->collection('test')->id('a')->published(true)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('b')->published(false)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('c')->published(true)->date(now()->subDay())->save();
Facades\Entry::make()->collection('test')->id('d')->published(false)->date(now()->subDay())->save();

$response = $this->get('/api/collections/test/entries')->assertSuccessful();
$this->assertCount(1, $response->getData()->data);
$response->assertJsonPath('data.0.id', 'c');
}

/** @test */
public function it_filters_out_past_entries_from_past_private_collection()
{
Facades\Config::set('statamic.api.resources.collections', true);

Facades\Collection::make('test')->dated(true)
->pastDateBehavior('private')
->futureDateBehavior('public')
->save();

Facades\Entry::make()->collection('test')->id('a')->published(true)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('b')->published(false)->date(now()->addDay())->save();
Facades\Entry::make()->collection('test')->id('c')->published(true)->date(now()->subDay())->save();
Facades\Entry::make()->collection('test')->id('d')->published(false)->date(now()->subDay())->save();

$response = $this->get('/api/collections/test/entries')->assertSuccessful();
$this->assertCount(1, $response->getData()->data);
$response->assertJsonPath('data.0.id', 'a');
}

/** @test */
public function it_can_filter_collection_entries_when_configuration_allows_for_it()
{
Expand Down
91 changes: 91 additions & 0 deletions tests/Data/Entries/EntryQueryBuilderTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -770,6 +770,97 @@ public function entries_are_found_using_lazy()
}

/** @test */
public function filtering_using_where_status_column_writes_deprecation_log()
{
$this->withoutDeprecationHandling();
$this->expectException(\ErrorException::class);
$this->expectExceptionMessage('Filtering by status is deprecated. Use whereStatus() instead.');

$this->createDummyCollectionAndEntries();

Entry::query()->where('collection', 'posts')->where('status', 'published')->get();
}

/** @test */
public function filtering_using_whereIn_status_column_writes_deprecation_log()
{
$this->withoutDeprecationHandling();
$this->expectException(\ErrorException::class);
$this->expectExceptionMessage('Filtering by status is deprecated. Use whereStatus() instead.');

$this->createDummyCollectionAndEntries();

Entry::query()->where('collection', 'posts')->whereIn('status', ['published'])->get();
}

/** @test */
public function filtering_by_unexpected_status_throws_exception()
{
$this->expectExceptionMessage('Invalid status [foo]');

Entry::query()->whereStatus('foo')->get();
}

/**
* @test
*
* @dataProvider filterByStatusProvider
*/
public function it_filters_by_status($status, $expected)
{
Collection::make('pages')->dated(false)->save();
EntryFactory::collection('pages')->id('page')->published(true)->create();
EntryFactory::collection('pages')->id('page-draft')->published(false)->create();

Collection::make('blog')->dated(true)->futureDateBehavior('private')->pastDateBehavior('public')->save();
EntryFactory::collection('blog')->id('blog-future')->published(true)->date(now()->addDay())->create();
EntryFactory::collection('blog')->id('blog-future-draft')->published(false)->date(now()->addDay())->create();
EntryFactory::collection('blog')->id('blog-past')->published(true)->date(now()->subDay())->create();
EntryFactory::collection('blog')->id('blog-past-draft')->published(false)->date(now()->subDay())->create();

Collection::make('events')->dated(true)->futureDateBehavior('public')->pastDateBehavior('private')->save();
EntryFactory::collection('events')->id('event-future')->published(true)->date(now()->addDay())->create();
EntryFactory::collection('events')->id('event-future-draft')->published(false)->date(now()->addDay())->create();
EntryFactory::collection('events')->id('event-past')->published(true)->date(now()->subDay())->create();
EntryFactory::collection('events')->id('event-past-draft')->published(false)->date(now()->subDay())->create();

Collection::make('calendar')->dated(true)->futureDateBehavior('public')->pastDateBehavior('public')->save();
EntryFactory::collection('calendar')->id('calendar-future')->published(true)->date(now()->addDay())->create();
EntryFactory::collection('calendar')->id('calendar-future-draft')->published(false)->date(now()->addDay())->create();
EntryFactory::collection('calendar')->id('calendar-past')->published(true)->date(now()->subDay())->create();
EntryFactory::collection('calendar')->id('calendar-past-draft')->published(false)->date(now()->subDay())->create();

$this->assertEquals($expected, Entry::query()->whereStatus($status)->get()->map->id->all());
}

public static function filterByStatusProvider()
{
return [
'draft' => ['draft', [
'page-draft',
'blog-future-draft',
'blog-past-draft',
'event-future-draft',
'event-past-draft',
'calendar-future-draft',
'calendar-past-draft',
]],
'published' => ['published', [
'page',
'blog-past',
'event-future',
'calendar-future',
'calendar-past',
]],
'scheduled' => ['scheduled', [
'blog-future',
]],
'expired' => ['expired', [
'event-past',
]],
];
}

public function values_can_be_plucked()
{
$this->createDummyCollectionAndEntries();
Expand Down
Loading