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