d54ea28a91dc53c2e096a13d38720dc3f088434d
[civicrm-core.git] / tests / phpunit / api / v4 / Spec / SpecFormatterTest.php
1 <?php
2
3 namespace api\v4\Spec;
4
5 use Civi\Api4\Service\Spec\CustomFieldSpec;
6 use Civi\Api4\Service\Spec\FieldSpec;
7 use Civi\Api4\Service\Spec\RequestSpec;
8 use Civi\Api4\Service\Spec\SpecFormatter;
9 use api\v4\UnitTestCase;
10
11 /**
12 * @group headless
13 */
14 class SpecFormatterTest extends UnitTestCase {
15
16 public function testSpecToArray() {
17 $spec = new RequestSpec('Contact', 'get');
18 $fieldName = 'last_name';
19 $field = new FieldSpec($fieldName, 'Contact');
20 $spec->addFieldSpec($field);
21 $arraySpec = SpecFormatter::specToArray($spec->getFields());
22
23 $this->assertEquals('String', $arraySpec[$fieldName]['data_type']);
24 }
25
26 /**
27 * @dataProvider arrayFieldSpecProvider
28 *
29 * @param array $fieldData
30 * @param string $expectedName
31 * @param string $expectedType
32 */
33 public function testArrayToField($fieldData, $expectedName, $expectedType) {
34 $field = SpecFormatter::arrayToField($fieldData, 'TestEntity');
35
36 $this->assertEquals($expectedName, $field->getName());
37 $this->assertEquals($expectedType, $field->getDataType());
38 }
39
40 public function testCustomFieldWillBeReturned() {
41 $customGroupId = 1432;
42 $customFieldId = 3333;
43 $name = 'MyFancyField';
44
45 $data = [
46 'custom_group_id' => $customGroupId,
47 'custom_group.name' => 'my_group',
48 'id' => $customFieldId,
49 'name' => $name,
50 'data_type' => 'String',
51 'html_type' => 'Multi-Select',
52 ];
53
54 /** @var \Civi\Api4\Service\Spec\CustomFieldSpec $field */
55 $field = SpecFormatter::arrayToField($data, 'TestEntity');
56
57 $this->assertInstanceOf(CustomFieldSpec::class, $field);
58 $this->assertEquals('my_group', $field->getCustomGroupName());
59 $this->assertEquals($customFieldId, $field->getCustomFieldId());
60 $this->assertEquals(\CRM_Core_DAO::SERIALIZE_SEPARATOR_BOOKEND, $field->getSerialize());
61 $this->assertEquals('Select', $field->getInputType());
62 $this->assertTrue($field->getInputAttrs()['multiple']);
63 }
64
65 /**
66 * @return array
67 */
68 public function arrayFieldSpecProvider() {
69 return [
70 [
71 [
72 'name' => 'Foo',
73 'title' => 'Bar',
74 'type' => \CRM_Utils_Type::T_STRING,
75 ],
76 'Foo',
77 'String',
78 ],
79 [
80 [
81 'name' => 'MyField',
82 'title' => 'Bar',
83 'type' => \CRM_Utils_Type::T_STRING,
84 // this should take precedence
85 'data_type' => 'Boolean',
86 ],
87 'MyField',
88 'Boolean',
89 ],
90 ];
91 }
92
93 }