CreateArticle.php in GraphQL 8.4
File
examples/graphql_composable/src/Plugin/GraphQL/DataProducer/CreateArticle.php
View source
<?php
namespace Drupal\graphql_composable\Plugin\GraphQL\DataProducer;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\graphql\Plugin\GraphQL\DataProducer\DataProducerPluginBase;
use Drupal\graphql_composable\GraphQL\Response\ArticleResponse;
use Drupal\node\Entity\Node;
use Symfony\Component\DependencyInjection\ContainerInterface;
class CreateArticle extends DataProducerPluginBase implements ContainerFactoryPluginInterface {
protected $currentUser;
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('current_user'));
}
public function __construct(array $configuration, string $plugin_id, array $plugin_definition, AccountInterface $current_user) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->currentUser = $current_user;
}
public function resolve(array $data) {
$response = new ArticleResponse();
if ($this->currentUser
->hasPermission("create article content")) {
$values = [
'type' => 'article',
'title' => $data['title'],
'body' => $data['description'],
];
$node = Node::create($values);
$node
->save();
$response
->setArticle($node);
}
else {
$response
->addViolation($this
->t('You do not have permissions to create articles.'));
}
return $response;
}
}