1<?php 2 3namespace Drupal\Tests\Core\Field; 4 5use Drupal\Core\Field\FieldInputValueNormalizerTrait; 6use Drupal\Tests\UnitTestCase; 7 8/** 9 * @coversDefaultClass \Drupal\Core\Field\FieldInputValueNormalizerTrait 10 * @group Field 11 */ 12class FieldInputValueNormalizerTraitTest extends UnitTestCase { 13 14 use FieldInputValueNormalizerTrait; 15 16 /** 17 * @dataProvider keyValueByDeltaTestCases 18 * @covers ::normalizeValue 19 */ 20 public function testKeyValueByDelta($input_value, $expected_value, $main_property_name = 'value') { 21 $this->assertEquals($expected_value, $this->normalizeValue($input_value, $main_property_name)); 22 } 23 24 /** 25 * Provides test cases for ::testKeyValueByDelta. 26 */ 27 public function keyValueByDeltaTestCases() { 28 return [ 29 'Integer' => [ 30 1, 31 [['value' => 1]], 32 ], 33 'Falsey integer' => [ 34 0, 35 [['value' => 0]], 36 ], 37 'String' => [ 38 'foo', 39 [['value' => 'foo']], 40 ], 41 'Empty string' => [ 42 '', 43 [['value' => '']], 44 ], 45 'Null' => [ 46 NULL, 47 [], 48 ], 49 'Empty field value' => [ 50 [], 51 [], 52 ], 53 'Single delta' => [ 54 ['value' => 'foo'], 55 [['value' => 'foo']], 56 ], 57 'Keyed delta' => [ 58 [['value' => 'foo']], 59 [['value' => 'foo']], 60 ], 61 'Multiple keyed deltas' => [ 62 [['value' => 'foo'], ['value' => 'bar']], 63 [['value' => 'foo'], ['value' => 'bar']], 64 ], 65 'No main property with keyed delta' => [ 66 [['foo' => 'bar']], 67 [['foo' => 'bar']], 68 NULL, 69 ], 70 'No main property with single delta' => [ 71 ['foo' => 'bar'], 72 [['foo' => 'bar']], 73 NULL, 74 ], 75 'No main property with empty array' => [ 76 [], 77 [], 78 NULL, 79 ], 80 ]; 81 } 82 83 /** 84 * @covers ::normalizeValue 85 */ 86 public function testScalarWithNoMainProperty() { 87 $this->expectException(\InvalidArgumentException::class); 88 $this->expectExceptionMessage('A main property is required when normalizing scalar field values.'); 89 $value = 'foo'; 90 $this->normalizeValue($value, NULL); 91 } 92 93 /** 94 * @covers ::normalizeValue 95 */ 96 public function testKeyValueByDeltaUndefinedVariables() { 97 $this->assertEquals([], $this->normalizeValue($undefined_variable, 'value')); 98 $this->assertEquals([], $this->normalizeValue($undefined_variable['undefined_key'], 'value')); 99 } 100 101} 102