Completed
Pull Request — master (#157)
by
unknown
01:35
created

DriverEntityWithBundleTest::setUp()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 13
nc 1
nop 0
1
<?php
2
3
namespace Drupal\Tests\Driver\Kernel\Drupal8\Entity;
4
5
use Drupal\Driver\Plugin\DriverFieldPluginManager;
6
use Drupal\Driver\Plugin\DriverEntityPluginManager;
7
use Drupal\Driver\Wrapper\Field\DriverFieldDrupal8;
8
use Drupal\Driver\Wrapper\Entity\DriverEntityDrupal8;
9
use Drupal\entity_test\Entity\EntityTestBundle;
10
11
/** Tests the entity plugin base class.
12
 *
13
 * @group driver
14
 */
15
class DriverEntityWithBundleTest extends DriverEntityKernelTestBase
16
{
17
18
  /**
19
   * Machine name of the entity type being tested.
20
   *
21
   * @string
22
   */
23
    protected $entityType = 'entity_test_with_bundle';
24
25
  /**
26
   * A field plugin manager object.
27
   *
28
   * @var \Drupal\Driver\Plugin\DriverPluginManagerInterface
29
   */
30
    protected $fieldPluginManager;
31
32
  /**
33
   * A field plugin manager object.
34
   *
35
   * @var \Drupal\Driver\Plugin\DriverPluginManagerInterface
36
   */
37
    protected $entityPluginManager;
38
39
    protected function setUp()
40
    {
41
        parent::setUp();
42
        $namespaces = \Drupal::service('container.namespaces');
43
        $cache_backend = \Drupal::service('cache.discovery');
44
        $module_handler = \Drupal::service('module_handler');
45
        $this->fieldPluginManager = new DriverFieldPluginManager($namespaces, $cache_backend, $module_handler, 8);
46
        $this->entityPluginManager = new DriverEntityPluginManager($namespaces, $cache_backend, $module_handler, 8);
47
        $this->installEntitySchema('entity_test_with_bundle');
48
        EntityTestBundle::create([
49
        'id' => 'test_bundle',
50
        'label' => 'Test label',
51
        'description' => 'Test description',
52
        ])->save();
53
    }
54
55
  /**
56
   * Test basic driver entity methods on an entity with bundles.
57
   */
58
    public function testLoadDeleteReload()
59
    {
60
        $value = $this->randomString();
61
        $fieldName = 'name';
62
        $processedName = 'now' . $value . 'processed';
63
        $field = new DriverFieldDrupal8(
64
            [['value' => $value]],
65
            $fieldName,
66
            $this->entityType
67
        );
68
        $entity = new DriverEntityDrupal8(
69
            $this->entityType
70
        );
71
        $entity->setBundle('test_bundle');
72
        $entity->setFields([$fieldName => $field]);
73
        $entity->save();
74
        $entityId = $entity->id();
75
76
77
        // Test load method.
78
        $alternateEntity = new DriverEntityDrupal8(
79
            $this->entityType
80
        );
81
        $alternateEntity->load($entityId);
82
        $this->assertFalse($alternateEntity->isNew());
83
        $this->assertEquals('test_bundle', $alternateEntity->bundle());
84
        $this->assertEquals($processedName, $alternateEntity->get($fieldName)->value);
0 ignored issues
show
Documentation Bug introduced by
The method get does not exist on object<Drupal\Driver\Wra...ty\DriverEntityDrupal8>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
85
86
        // Test reload method
87
        $newValue = $this->randomString();
88
        $newProcessedName = 'now' . $newValue . 'processed';
89
        $entity->set($fieldName, [['value' => $newValue]]);
90
        $entity->save();
91
        $entities = $this->storage->loadByProperties([$fieldName => $newProcessedName]);
92
        $this->assertEquals(1, count($entities));
93
        // Alternate entity has stale value until reloaded.
94
        $this->assertNotEquals($newProcessedName, $alternateEntity->get($fieldName)->value);
0 ignored issues
show
Documentation Bug introduced by
The method get does not exist on object<Drupal\Driver\Wra...ty\DriverEntityDrupal8>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
95
        $alternateEntity->reload();
96
        $this->assertEquals($newProcessedName, $alternateEntity->get($fieldName)->value);
0 ignored issues
show
Documentation Bug introduced by
The method get does not exist on object<Drupal\Driver\Wra...ty\DriverEntityDrupal8>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
97
98
        // Test delete method.
99
        $alternateEntity->delete();
100
        $entities = $this->storage->loadByProperties([$fieldName => $newProcessedName]);
101
        $this->assertEquals(0, count($entities));
102
    }
103
104
  /**
105
   * Test setting a field on an entity with bundle.
106
   */
107
    public function testEntityWithBundle()
108
    {
109
        $value = $this->randomString();
110
        $fieldName = 'name';
111
112
        // Also tests passing the bundle in the create method and the constructor.
113
        $entity = DriverEntityDrupal8::create(
114
            [$fieldName => [['value' => $value]]],
115
            $this->entityType,
116
            'test_bundle'
117
        )->save();
118
119
        // Test bundle set properly
120
        $this->assertEquals($entity->bundle(), 'test_bundle');
121
122
        // The test driverfield plugin has been matched,  which mutates the text.
123
        $processedName = 'now' . $value . 'processed';
124
        $entities = $this->storage->loadByProperties(['name' => $processedName]);
125
        $this->assertEquals(1, count($entities));
126
    }
127
128
  /**
129
   * Test setting a nonexistent bundle.
130
   */
131 View Code Duplication
    public function testSetNonexistentBundle()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
132
    {
133
        $entity = new DriverEntityDrupal8(
134
            $this->entityType
135
        );
136
        $this->setExpectedException(\Exception::class, "'nonexistent_bundle' could not be identified as a bundle of the '" . $this->entityType);
137
        $entity->setBundle('nonexistent_bundle');
138
    }
139
140
  /**
141
   * Test setting a non existent bundle as a field.
142
   */
143 View Code Duplication
    public function testSetNonExistentBundleByField()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
144
    {
145
        $entity = new DriverEntityDrupal8(
146
            $this->entityType
147
        );
148
149
        $this->setExpectedException(\Exception::class, "No entity of type 'entity_test_bundle' has id or label matching");
150
        $entity->set('type', ['nonexistent bundle']);
151
    }
152
153
  /**
154
   * Test modifying an already set the bundle.
155
   */
156
    public function testModifyBundle()
157
    {
158
        EntityTestBundle::create([
159
        'id' => 'other_bundle',
160
        'label' => 'Other label',
161
        'description' => 'Other description',
162
        ])->save();
163
        $entity = new DriverEntityDrupal8(
164
            $this->entityType
165
        );
166
167
        // Test exception when explicitly setting already set bundle bundle
168
        $entity->setBundle('test_bundle');
169
        $entity->getFinalPlugin();
170
        $this->setExpectedException(\Exception::class, "Cannot change entity bundle after final plugin discovery");
171
        $entity->setBundle('other_bundle');
172
    }
173
174
  /**
175
   * Test can identify bundle by label.
176
   */
177
    public function testEntityWithBundleByLabel()
178
    {
179
        $entity = new DriverEntityDrupal8(
180
            $this->entityType
181
        );
182
        // test_bundle has the label "Test label"
183
        $entity->setBundle('test label');
184
        $this->assertEquals($entity->bundle(), 'test_bundle');
185
    }
186
187
  /**
188
   * Test extracting a bundle from among other fields, for various formats.
189
   */
190
    public function testCanExtractBundleFromFields()
191
    {
192
        $variants = [
193
        [['target_id' => 'Test label']],
194
        ['target_id' => 'Test label'],
195
        [['Test label']],
196
        ['Test label'],
197
        ];
198
199
        foreach ($variants as $variant) {
200
            // Test passing bundle as raw field.
201
            $this->assertCanExtractBundleFromFields($variant);
202
203
            // Test passing bundle as driverfield object.
204
            $field = new DriverFieldDrupal8(
205
                $variant,
206
                'type',
207
                $this->entityType,
208
                'test_bundle'
209
            );
210
            $this->assertCanExtractBundleFromFields($field);
211
        }
212
    }
213
214
  /**
215
   * Test extracting a bundle in a particular format from among other fields.
216
   *
217
   * @param array|object $variant
218
   *   A representation of a field identifying an entity's bundle.
219
   */
220
    public function assertCanExtractBundleFromFields($variant)
221
    {
222
        $value = $this->randomString();
223
        $fields = [
224
        'name' => [['value' => $value]],
225
        'type' => $variant,
226
        ];
227
228
        $entity = DriverEntityDrupal8::create(
229
            $fields,
230
            $this->entityType
231
        )->save();
232
233
        // Test bundle set properly
234
        $this->assertEquals($entity->bundle(), 'test_bundle');
235
236
        // The test driverfield plugin has been matched,  which mutates the text.
237
        $processedName = 'now' . $value . 'processed';
238
        $entities = $this->storage->loadByProperties(['name' => $processedName]);
239
240
        $bundleString = str_replace(PHP_EOL, '', print_r($variant, true));
241
        $message = "Entity not created correctly when bundle input has value " . $bundleString;
242
        $this->assertEquals(1, count($entities), $message);
243
    }
244
}
245