View source
<?php
declare (strict_types=1);
namespace Drupal\Tests\og\Kernel\Entity;
use Drupal\field\Entity\FieldConfig;
use Drupal\node\Entity\NodeType;
use Drupal\KernelTests\KernelTestBase;
use Drupal\og\Og;
use Drupal\og\OgGroupAudienceHelperInterface;
use Drupal\og\Plugin\OgFields\AccessField;
class FieldCreateTest extends KernelTestBase {
public static $modules = [
'user',
'field',
'node',
'options',
'system',
'og',
'og_test',
];
protected $bundles;
protected function setUp() : void {
parent::setUp();
$this
->installConfig([
'og',
]);
$this
->installEntitySchema('og_membership');
$this
->installEntitySchema('user');
$this
->installEntitySchema('node');
for ($i = 0; $i <= 4; $i++) {
$bundle = NodeType::create([
'type' => mb_strtolower($this
->randomMachineName()),
'name' => $this
->randomString(),
]);
$bundle
->save();
$this->bundles[] = $bundle
->id();
}
}
public function testValidFields() {
$field_names = [
OgGroupAudienceHelperInterface::DEFAULT_FIELD,
AccessField::DEFAULT_FIELD,
];
foreach ($field_names as $field_name) {
$bundle = $this->bundles[0];
Og::CreateField($field_name, 'node', $bundle);
$this
->assertNotNull(FieldConfig::loadByName('node', $bundle, $field_name));
}
$bundle = $this->bundles[1];
Og::CreateField(OgGroupAudienceHelperInterface::DEFAULT_FIELD, 'node', $bundle, [
'field_config' => [
'label' => 'Other groups dummy',
],
]);
$this
->assertEquals(FieldConfig::loadByName('node', $bundle, OgGroupAudienceHelperInterface::DEFAULT_FIELD)
->label(), 'Other groups dummy');
$bundle = $this->bundles[2];
Og::CreateField(OgGroupAudienceHelperInterface::DEFAULT_FIELD, 'node', $bundle, [
'field_name' => 'override_name',
]);
$this
->assertNotNull(FieldConfig::loadByName('node', $bundle, 'override_name')
->id());
$bundle = $this->bundles[3];
Og::CreateField('entity_restricted', 'node', $bundle);
$this
->assertNotNull(FieldConfig::loadByName('node', $bundle, 'entity_restricted')
->id());
}
public function testInvalidFields() {
$bundle = $this->bundles[0];
try {
Og::CreateField('undefined_field_name', 'node', $bundle);
$this
->fail('Undefined field name was attached');
} catch (\Exception $e) {
}
try {
Og::CreateField('entity_restricted', 'user', 'user');
$this
->fail('Field was attached to a prohibited entity type.');
} catch (\Exception $e) {
}
}
}