Commit 0666a1f9 authored by Klaus Purer's avatar Klaus Purer
Browse files

fix(dataproducer): Fix entity label handling (by mxr576)

parent f12daab4
Loading
Loading
Loading
Loading
+18 −3
Original line number Diff line number Diff line
@@ -3,6 +3,8 @@
namespace Drupal\graphql\Plugin\GraphQL\DataProducer\Entity;

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\graphql\GraphQL\Execution\FieldContext;
use Drupal\graphql\Plugin\DataProducerPluginCachingInterface;
use Drupal\graphql\Plugin\GraphQL\DataProducer\DataProducerPluginBase;

@@ -19,7 +21,12 @@ use Drupal\graphql\Plugin\GraphQL\DataProducer\DataProducerPluginBase;
 *   consumes = {
 *     "entity" = @ContextDefinition("entity",
 *       label = @Translation("Entity")
 *     )
 *     ),
 *     "access_user" = @ContextDefinition("entity:user",
 *       label = @Translation("User"),
 *       required = FALSE,
 *       default_value = NULL
 *     ),
 *   }
 * )
 */
@@ -29,11 +36,19 @@ class EntityLabel extends DataProducerPluginBase implements DataProducerPluginCa
   * Resolver.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   * @param \Drupal\Core\Session\AccountInterface|null $accessUser
   * @param \Drupal\graphql\GraphQL\Execution\FieldContext $context
   *
   * @return string|null
   */
  public function resolve(EntityInterface $entity) {
  public function resolve(EntityInterface $entity, ?AccountInterface $accessUser, FieldContext $context) {
    /** @var \Drupal\Core\Access\AccessResultInterface $accessResult */
    $accessResult = $entity->access('view label', $accessUser, TRUE);
    $context->addCacheableDependency($accessResult);
    if ($accessResult->isAllowed()) {
      return $entity->label();
    }
    return NULL;
  }

}
+24 −0
Original line number Diff line number Diff line
@@ -2,6 +2,7 @@

namespace Drupal\Tests\graphql\Kernel\DataProducer;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Url;
@@ -199,9 +200,32 @@ class EntityTest extends GraphQLTestBase {
      ->method('label')
      ->willReturn('Dummy label');

    $this->entity->expects($this->exactly(2))
      ->method('access')
      ->willReturnCallback(static function (): AccessResult {
        static $counter = 0;
        switch ($counter) {
          case 0:
            $counter++;
            return AccessResult::allowed();

          case 1:
            $counter++;
            return AccessResult::forbidden();

          default:
            throw new \LogicException('The access() method should not have been called more than twice.');
        }
      })
      ->with('view label', NULL, TRUE);

    $this->assertEquals('Dummy label', $this->executeDataProducer('entity_label', [
      'entity' => $this->entity,
    ]));

    $this->assertNull($this->executeDataProducer('entity_label', [
      'entity' => $this->entity,
    ]));
  }

  /**