View source
<?php
namespace Drupal\graphql_core\Plugin\GraphQL\Mutations\Entity;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Render\RenderContext;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\graphql\GraphQL\Execution\ResolveContext;
use Drupal\graphql_core\GraphQL\EntityCrudOutputWrapper;
use Drupal\graphql\Plugin\GraphQL\Mutations\MutationPluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use GraphQL\Type\Definition\ResolveInfo;
abstract class CreateEntityBase extends MutationPluginBase implements ContainerFactoryPluginInterface {
use DependencySerializationTrait;
use StringTranslationTrait;
protected $entityTypeManager;
protected $renderer;
public static function create(ContainerInterface $container, array $configuration, $pluginId, $pluginDefinition) {
return new static($configuration, $pluginId, $pluginDefinition, $container
->get('entity_type.manager'), $container
->get('renderer'));
}
public function __construct(array $configuration, $pluginId, $pluginDefinition, EntityTypeManagerInterface $entityTypeManager, RendererInterface $renderer) {
parent::__construct($configuration, $pluginId, $pluginDefinition);
$this->entityTypeManager = $entityTypeManager;
$this->renderer = $renderer;
}
public function resolve($value, array $args, ResolveContext $context, ResolveInfo $info) {
return $this->renderer
->executeInRenderContext(new RenderContext(), function () use ($value, $args, $context, $info) {
$entityTypeId = $this->pluginDefinition['entity_type'];
$input = $this
->extractEntityInput($value, $args, $context, $info);
$entityDefinition = $this->entityTypeManager
->getDefinition($entityTypeId);
if ($entityDefinition
->hasKey('bundle')) {
$bundleName = $this->pluginDefinition['entity_bundle'];
$bundleKey = $entityDefinition
->getKey('bundle');
$input[$bundleKey] = $bundleName;
}
$storage = $this->entityTypeManager
->getStorage($entityTypeId);
$entity = $storage
->create($input);
return $this
->resolveOutput($entity, $args, $info);
});
}
protected abstract function extractEntityInput($value, array $args, ResolveContext $context, ResolveInfo $info);
protected function resolveOutput(EntityInterface $entity, array $args, ResolveInfo $info) {
if (!$entity
->access('create')) {
return new EntityCrudOutputWrapper(NULL, NULL, [
$this
->t('You do not have the necessary permissions to create entities of this type.'),
]);
}
if ($entity instanceof ContentEntityInterface) {
if (($violations = $entity
->validate()) && $violations
->count()) {
return new EntityCrudOutputWrapper(NULL, $violations);
}
}
if (($status = $entity
->save()) && $status === SAVED_NEW) {
return new EntityCrudOutputWrapper($entity);
}
return NULL;
}
}