Version 1
[yaffs-website] / web / core / modules / field / tests / src / Functional / FieldTestBase.php
1 <?php
2
3 namespace Drupal\Tests\field\Functional;
4
5 use Drupal\Core\Entity\EntityInterface;
6 use Drupal\Core\Language\LanguageInterface;
7 use Drupal\Tests\BrowserTestBase;
8
9 /**
10  * Parent class for Field API tests.
11  */
12 abstract class FieldTestBase extends BrowserTestBase {
13
14   /**
15    * Generate random values for a field_test field.
16    *
17    * @param $cardinality
18    *   Number of values to generate.
19    * @return
20    *   An array of random values, in the format expected for field values.
21    */
22   public function _generateTestFieldValues($cardinality) {
23     $values = [];
24     for ($i = 0; $i < $cardinality; $i++) {
25       // field_test fields treat 0 as 'empty value'.
26       $values[$i]['value'] = mt_rand(1, 127);
27     }
28     return $values;
29   }
30
31   /**
32    * Assert that a field has the expected values in an entity.
33    *
34    * This function only checks a single column in the field values.
35    *
36    * @param EntityInterface $entity
37    *   The entity to test.
38    * @param $field_name
39    *   The name of the field to test
40    * @param $expected_values
41    *   The array of expected values.
42    * @param $langcode
43    *   (Optional) The language code for the values. Defaults to
44    *   \Drupal\Core\Language\LanguageInterface::LANGCODE_DEFAULT.
45    * @param $column
46    *   (Optional) The name of the column to check. Defaults to 'value'.
47    */
48   public function assertFieldValues(EntityInterface $entity, $field_name, $expected_values, $langcode = LanguageInterface::LANGCODE_DEFAULT, $column = 'value') {
49     // Re-load the entity to make sure we have the latest changes.
50     $storage = $this->container->get('entity_type.manager')
51       ->getStorage($entity->getEntityTypeId());
52     $storage->resetCache([$entity->id()]);
53     $e = $storage->load($entity->id());
54
55     $field = $values = $e->getTranslation($langcode)->$field_name;
56     // Filter out empty values so that they don't mess with the assertions.
57     $field->filterEmptyItems();
58     $values = $field->getValue();
59     $this->assertEqual(count($values), count($expected_values), 'Expected number of values were saved.');
60     foreach ($expected_values as $key => $value) {
61       $this->assertEqual($values[$key][$column], $value, format_string('Value @value was saved correctly.', ['@value' => $value]));
62     }
63   }
64
65 }