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

DriverEntityTest   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 268
Duplicated Lines 26.12 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 3
dl 70
loc 268
rs 10
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A setUp() 0 4 1
B testField() 0 26 1
A assertEntitySetFieldsWithArray() 11 11 1
A assertEntitySetFieldsWithObject() 0 16 1
A assertEntitySet() 11 11 1
B assertEntityWithName() 0 44 1
A testSetEntityPlugin() 0 20 1
A testCreate() 16 16 1
A testEntityTypeLabel() 16 16 1
A testEntityTypeWithoutUnderscores() 16 16 1
A recursiveReplace() 0 11 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Drupal\Tests\Driver\Kernel\Drupal8\Entity;
4
5
use Drupal\Core\Entity\EntityInterface;
6
use Drupal\Driver\Wrapper\Field\DriverFieldDrupal8;
7
use Drupal\Driver\Wrapper\Entity\DriverEntityDrupal8;
8
9
/** Tests the entity plugin base class.
10
 *
11
 * @group driver
12
 */
13
class DriverEntityTest extends DriverEntityKernelTestBase
14
{
15
16
  /**
17
   * Machine name of the entity type being tested.
18
   *
19
   * @string
20
   */
21
    protected $entityType = 'entity_test';
22
23
  /**
24
   * A field plugin manager object.
25
   *
26
   * @var \Drupal\Driver\Plugin\DriverPluginManagerInterface
27
   */
28
    protected $fieldPluginManager;
29
30
  /**
31
   * A field plugin manager object.
32
   *
33
   * @var \Drupal\Driver\Plugin\DriverPluginManagerInterface
34
   */
35
    protected $entityPluginManager;
36
37
    protected function setUp()
38
    {
39
        parent::setUp();
40
    }
41
42
  /**
43
   * Test various ways of setting field values on entities.
44
   */
45
    public function testField()
46
    {
47
        // Value & property explicit.
48
        $fieldValues =  [['value' => 'NAME']];
49
        $this->assertEntitySetFieldsWithObject($fieldValues);
50
        $this->assertEntitySetFieldsWithArray($fieldValues);
51
        $this->assertEntitySet($fieldValues);
52
53
        // Value explicit, property assumed.
54
        $fieldValues =  [['NAME']];
55
        $this->assertEntitySetFieldsWithObject($fieldValues);
56
        $this->assertEntitySetFieldsWithArray($fieldValues);
57
        $this->assertEntitySet($fieldValues);
58
59
        // Single value assumed, property explicit.
60
        $fieldValues =  ['value' => 'NAME'];
61
        $this->assertEntitySetFieldsWithObject($fieldValues);
62
        $this->assertEntitySetFieldsWithArray($fieldValues);
63
        $this->assertEntitySet($fieldValues);
64
65
        // Single value assumed, property assumed.
66
        $fieldValues =  'NAME';
67
        $this->assertEntitySetFieldsWithObject($fieldValues);
68
        $this->assertEntitySetFieldsWithArray($fieldValues);
69
        $this->assertEntitySet($fieldValues);
70
    }
71
72
  /**
73
   * Assert that an entity is created using the setFields method and an field
74
   * values array.
75
   */
76 View Code Duplication
    protected function assertEntitySetFieldsWithArray($fieldValues)
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...
77
    {
78
        $value = $this->randomString();
79
        $fieldValues = $this->recursiveReplace('NAME', $value, $fieldValues);
80
        $fieldName = 'name';
81
        $entity = new DriverEntityDrupal8(
82
            $this->entityType
83
        );
84
        $entity->setFields([$fieldName => $fieldValues]);
85
        $this->assertEntityWithName($value, $fieldName, $entity);
86
    }
87
88
  /**
89
   * Assert that an entity is created using the setFields method and a driver
90
   * field object.
91
   */
92
    protected function assertEntitySetFieldsWithObject($fieldValues)
93
    {
94
        $value = $this->randomString();
95
        $fieldValues = $this->recursiveReplace('NAME', $value, $fieldValues);
96
        $fieldName = 'name';
97
        $field = new DriverFieldDrupal8(
98
            $fieldValues,
99
            $fieldName,
100
            $this->entityType
101
        );
102
        $entity = new DriverEntityDrupal8(
103
            $this->entityType
104
        );
105
        $entity->setFields([$fieldName => $field]);
106
        $this->assertEntityWithName($value, $fieldName, $entity);
107
    }
108
109
  /**
110
   * Assert that an entity is created using the set method.
111
   */
112 View Code Duplication
    protected function assertEntitySet($fieldValues)
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...
113
    {
114
        $value = $this->randomString();
115
        $fieldValues = $this->recursiveReplace('NAME', $value, $fieldValues);
116
        $fieldName = 'name';
117
        $entity = new DriverEntityDrupal8(
118
            $this->entityType
119
        );
120
        $entity->set($fieldName, $fieldValues);
121
        $this->assertEntityWithName($value, $fieldName, $entity);
122
    }
123
124
  /**
125
   * Assert that an entity is created & wrapped with a specified name.
126
   */
127
    protected function assertEntityWithName($value, $fieldName, $entity)
128
    {
129
        $value = $this->randomString();
130
        $fieldName = 'name';
131
132
        $field = new DriverFieldDrupal8(
133
            [['value' => $value]],
134
            $fieldName,
135
            $this->entityType
136
        );
137
138
        // Test setFields.
139
        $entity = new DriverEntityDrupal8(
140
            $this->entityType
141
        );
142
        $entity->setFields([$fieldName => $field]);
143
144
        $this->assertTrue($entity->isNew());
145
        $this->assertEquals($entity->getEntityTypeId(), $this->entityType);
146
        $this->assertEquals($entity->bundle(), $this->entityType);
147
148
        // The generic driverentity plugin should have been discovered and matched.
149
        // The test plugin has a lower weight, so is ignored.
150
        $this->assertEquals('generic8', $entity->getFinalPlugin()->getPluginId());
151
152
        // Test save method.
153
        $entity->save();
154
        // The test driverfield plugin has been matched,  which mutates the text.
155
        $processedName = 'now' . $value . 'processed';
156
        $entities = $this->storage->loadByProperties([$fieldName => $processedName]);
157
        $this->assertEquals(1, count($entities));
158
159
        // Test real drupal entity is attached to wrapper.
160
        $drupalEntity = $entity->getEntity();
161
        $this->assertTrue($drupalEntity instanceof EntityInterface);
0 ignored issues
show
Bug introduced by
The class Drupal\Core\Entity\EntityInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
162
        $this->assertFalse($drupalEntity->isNew());
163
        $this->assertEquals(array_shift($entities)->id(), $drupalEntity->id());
164
165
        $this->assertFalse($entity->isNew());
166
167
        // Test calling Drupal entity methods via the wrapper.
168
        // isDefaultKey comes from ContentEntityBase which entity_test inherits.
169
        $this->assertTrue($entity->isDefaultRevision());
0 ignored issues
show
Documentation Bug introduced by
The method isDefaultRevision 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...
170
    }
171
172
  /**
173
   * Test additional driver entity methods.
174
   */
175
    public function testSetEntityPlugin()
176
    {
177
        // Test setting entity type and bundle explicitly, not in construct method.
178
        $entity = new DriverEntityDrupal8(
179
            $this->entityType
180
        );
181
182
        // Test setEntityPlugin, bypassing normal plugin discovery and matching,
183
        // instead assigning the 'test' plugin.
184
        $config = [
185
        'type' => $this->entityType,
186
        'bundle' => $this->entityType,
187
        'fieldPluginManager' => $this->fieldPluginManager
188
        ];
189
        // Normally the test plugin is ignored because it is a lower weight than
190
        // the generic plugin. Test if we can explicitly set it.
191
        $plugin = $this->entityPluginManager->createInstance('test8', $config);
192
        $entity->setFinalPlugin($plugin);
193
        $this->assertEquals('test8', $entity->getFinalPlugin()->getPluginId());
194
    }
195
196
  /**
197
   * Test create method.
198
   */
199 View Code Duplication
    public function testCreate()
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...
200
    {
201
        $value = $this->randomString();
202
        $fieldName = 'name';
203
        $fields = [$fieldName=> [['value' => $value]]];
204
205
        // Test create method.
206
        $entity = DriverEntityDrupal8::create(
0 ignored issues
show
Unused Code introduced by
$entity is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
207
            $fields,
208
            $this->entityType
209
        )->save();
210
        // The test driverfield plugin has been matched,  which mutates the text.
211
        $processedName = 'now' . $value . 'processed';
212
        $entities = $this->storage->loadByProperties(['name' => $processedName]);
213
        $this->assertEquals(1, count($entities));
214
    }
215
216
  /**
217
   * Test identifying entity type by label.
218
   */
219 View Code Duplication
    public function testEntityTypeLabel()
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...
220
    {
221
        $value = $this->randomString();
222
        $fieldName = 'name';
223
        $fields = [$fieldName=> [['value' => $value]]];
224
225
        // "Test entity" is the label of the entity_test entity type.
226
        $entity = DriverEntityDrupal8::create(
0 ignored issues
show
Unused Code introduced by
$entity is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
227
            $fields,
228
            "Test entity"
229
        )->save();
230
        // The test driverfield plugin has been matched,  which mutates the text.
231
        $processedName = 'now' . $value . 'processed';
232
        $entities = $this->storage->loadByProperties(['name' => $processedName]);
233
        $this->assertEquals(1, count($entities));
234
    }
235
236
  /**
237
   * Test identifying entity type by machine name without underscores.
238
   */
239 View Code Duplication
    public function testEntityTypeWithoutUnderscores()
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...
240
    {
241
        $value = $this->randomString();
242
        $fieldName = 'name';
243
        $fields = [$fieldName=> [['value' => $value]]];
244
245
        // Instead of "entity_test", try capitalised and without underscores.
246
        $entity = DriverEntityDrupal8::create(
0 ignored issues
show
Unused Code introduced by
$entity is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
247
            $fields,
248
            "ENTITY TEST"
249
        )->save();
250
        // The test driverfield plugin has been matched,  which mutates the text.
251
        $processedName = 'now' . $value . 'processed';
252
        $entities = $this->storage->loadByProperties(['name' => $processedName]);
253
        $this->assertEquals(1, count($entities));
254
    }
255
256
  /**
257
   * Replace values in strings or recursively in arrays.
258
   *
259
   * @param string $find
260
   *   The string to be replaced.
261
   * @param string $replace
262
   *   The string to replace with.
263
   * @param array|string $heap
264
   *   The heap to iterate over.
265
   *
266
   * @return array|string
267
   *   The heap with the strings replaced.
268
   */
269
    protected function recursiveReplace($find, $replace, $heap)
270
    {
271
        if (!is_array($heap)) {
272
            return str_replace($find, $replace, $heap);
273
        }
274
        $newArray = [];
275
        foreach ($heap as $key => $value) {
276
            $newArray[$key] = $this->recursiveReplace($find, $replace, $value);
277
        }
278
        return $newArray;
279
    }
280
}
281