View source
<?php
namespace Drupal\Tests\jsonapi\Kernel\ResourceType;
use Drupal\Tests\jsonapi\Kernel\JsonapiKernelTestBase;
use Drupal\node\Entity\NodeType;
class RelatedResourceTypesTest extends JsonapiKernelTestBase {
public static $modules = [
'node',
'jsonapi',
'serialization',
'system',
'user',
'field',
];
protected $resourceTypeRepository;
protected $fooType;
protected $barType;
protected function setUp() {
parent::setUp();
$this
->installEntitySchema('node');
$this
->installEntitySchema('user');
$this
->installSchema('system', [
'sequences',
]);
$this
->installSchema('node', [
'node_access',
]);
$this
->installSchema('user', [
'users_data',
]);
NodeType::create([
'type' => 'foo',
])
->save();
NodeType::create([
'type' => 'bar',
])
->save();
$this
->createEntityReferenceField('node', 'foo', 'field_ref_bar', 'Bar Reference', 'node', 'default', [
'target_bundles' => [
'bar',
],
]);
$this
->createEntityReferenceField('node', 'foo', 'field_ref_foo', 'Foo Reference', 'node', 'default', [
'target_bundles' => [
'foo',
],
]);
$this
->createEntityReferenceField('node', 'foo', 'field_ref_any', 'Any Bundle Reference', 'node', 'default', [
'target_bundles' => NULL,
]);
$this->resourceTypeRepository = $this->container
->get('jsonapi.resource_type.repository');
}
public function testGetRelatableResourceTypes($resource_type_name, $relatable_type_names) {
$test_fields = [
'field_ref_foo',
'field_ref_bar',
'field_ref_any',
];
$resource_type = $this->resourceTypeRepository
->getByTypeName($resource_type_name);
$subjects = array_intersect_key($resource_type
->getRelatableResourceTypes(), array_flip($test_fields));
foreach ($test_fields as $field_name) {
if (isset($subjects[$field_name])) {
$subjects[$field_name] = array_map(function ($resource_type) {
return $resource_type
->getTypeName();
}, $subjects[$field_name]);
}
}
$this
->assertArraySubset($relatable_type_names, $subjects);
}
public function getRelatableResourceTypesProvider() {
return [
[
'node--foo',
[
'field_ref_foo' => [
'node--foo',
],
'field_ref_bar' => [
'node--bar',
],
'field_ref_any' => [
'node--foo',
'node--bar',
],
],
],
[
'node--bar',
[],
],
];
}
public function testGetRelatableResourceTypesByField($entity_type_id, $bundle, $field) {
$resource_type = $this->resourceTypeRepository
->get($entity_type_id, $bundle);
$relatable_types = $resource_type
->getRelatableResourceTypes();
$this
->assertSame($relatable_types[$field], $resource_type
->getRelatableResourceTypesByField($field));
}
public function getRelatableResourceTypesByFieldProvider() {
return [
[
'node',
'foo',
'field_ref_foo',
],
[
'node',
'foo',
'field_ref_bar',
],
[
'node',
'foo',
'field_ref_any',
],
];
}
}