graphql_compose-1.0.0-beta20/src/Plugin/GraphQL/DataProducer/EntityUnpublishedFilter.php
src/Plugin/GraphQL/DataProducer/EntityUnpublishedFilter.php
<?php
declare(strict_types=1);
namespace Drupal\graphql_compose\Plugin\GraphQL\DataProducer;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Plugin\Context\ContextDefinition;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\graphql\Attribute\DataProducer;
use Drupal\graphql\GraphQL\Execution\FieldContext;
use Drupal\graphql\Plugin\GraphQL\DataProducer\DataProducerPluginBase;
use Drupal\graphql_compose\Utility\ComposeConfig;
/**
* Remove unpublished entities (ignoring permissions) from a results array.
*/
#[DataProducer(
id: "entity_unpublished_filter",
name: new TranslatableMarkup("Filter out unpublished entities."),
description: new TranslatableMarkup("Check published status on results."),
produces: new ContextDefinition(
data_type: "any",
label: new TranslatableMarkup("Final field results"),
),
consumes: [
"value" => new ContextDefinition(
data_type: "any",
label: new TranslatableMarkup("Field results to filter"),
),
],
)]
class EntityUnpublishedFilter extends DataProducerPluginBase {
/**
* Optionally remove unpublished entities from a results array.
*
* Normal access rights still apply.
* We remove unpublished entities for editors using the frontend.
*
* @param array $results
* The results form a field plugin type to process.
* @param \Drupal\graphql\GraphQL\Execution\FieldContext $context
* The cache context.
*
* @return mixed
* The filtered results.
*/
public function resolve(array $results, FieldContext $context) {
// Feature flip to hide unpublished content in graphql from editors.
$exclude = ComposeConfig::get('settings.exclude_unpublished', FALSE);
// Keep all results if we are in preview mode.
$preview = $context->getContextValue('preview') ?: FALSE;
if (!$exclude || $preview) {
return $results;
}
return array_filter(
$results,
fn ($result) => ($result instanceof EntityPublishedInterface)
? ($result->isPublished() || $result->isNew())
: TRUE,
);
}
}
