View source
<?php
namespace Drupal\Tests\social_graphql\Kernel;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\file\Entity\File;
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
use Drupal\user\Entity\Role;
use GraphQL\Executor\Promise\Adapter\SyncPromise;
class MediaBridgeFileTest extends FieldKernelTestBase {
public static $modules = [
'file',
'image',
'graphql',
'social_graphql',
];
protected $dataProducerPluginManager;
protected $image;
protected function setUp() {
parent::setUp();
$this
->installEntitySchema('user');
$this
->installConfig([
'user',
]);
$anonymous_role = Role::load(Role::ANONYMOUS_ID);
$anonymous_role
->grantPermission('access content');
$anonymous_role
->save();
$this
->installEntitySchema('file');
$this
->installSchema('file', [
'file_usage',
]);
FieldStorageConfig::create([
'field_name' => 'image_test',
'entity_type' => 'entity_test',
'type' => 'image',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
])
->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'image_test',
'bundle' => 'entity_test',
'settings' => [
'file_extensions' => 'jpg',
],
])
->save();
\Drupal::service('file_system')
->copy($this->root . '/core/misc/druplicon.png', 'public://social_graphql-example.jpg');
$this->image = File::create([
'uri' => 'public://social_graphql-example.jpg',
]);
$this->image
->save();
$this->imageFactory = $this->container
->get('image.factory');
$this->dataProducerPluginManager = $this->container
->get('plugin.manager.graphql.data_producer');
}
public function testImageField() {
$data_producer = $this->dataProducerPluginManager
->createInstance('media_bridge');
$entity = EntityTest::create();
$entity->image_test->target_id = $this->image
->id();
$entity->image_test->alt = $alt = $this
->randomMachineName();
$entity->image_test->title = $title = $this
->randomMachineName();
$entity->name->value = $this
->randomMachineName();
$entity
->save();
$entity = EntityTest::load($entity
->id());
$file_field = $entity
->get('image_test')
->first();
$resolved_uuid = $this
->await($data_producer
->resolve($file_field, 'id'));
self::assertEquals($this->image
->uuid(), $resolved_uuid);
$resolved_url = $this
->await($data_producer
->resolve($file_field, 'url'));
self::assertEquals($GLOBALS['base_url'] . '/' . $this->siteDirectory . '/files/social_graphql-example.jpg', $resolved_url);
$resolved_title = $this
->await($data_producer
->resolve($file_field, 'title'));
self::assertEquals($title, $resolved_title);
$resolved_alt = $this
->await($data_producer
->resolve($file_field, 'alt'));
self::assertEquals($alt, $resolved_alt);
}
protected function await($value) {
if ($value instanceof SyncPromise) {
$value::runQueue();
return $value->result;
}
return $value;
}
}