Commit | Line | Data |
---|---|---|
19b53e5b C |
1 | <?php |
2 | ||
380f3545 TO |
3 | /* |
4 | +--------------------------------------------------------------------+ | |
7d61e75f | 5 | | Copyright CiviCRM LLC. All rights reserved. | |
380f3545 | 6 | | | |
7d61e75f TO |
7 | | This work is published under the GNU AGPLv3 license with some | |
8 | | permitted exceptions and without any warranty. For full license | | |
9 | | and copyright information, see https://civicrm.org/licensing | | |
380f3545 TO |
10 | +--------------------------------------------------------------------+ |
11 | */ | |
12 | ||
13 | /** | |
14 | * | |
15 | * @package CRM | |
ca5cec67 | 16 | * @copyright CiviCRM LLC https://civicrm.org/licensing |
380f3545 TO |
17 | */ |
18 | ||
19 | ||
19b53e5b C |
20 | namespace api\v4\Traits; |
21 | ||
22 | /** | |
23 | * This probably should be a separate class | |
24 | */ | |
25 | trait TestDataLoaderTrait { | |
26 | ||
27 | /** | |
28 | * @var array | |
29 | * References to entities used for loading test data | |
30 | */ | |
31 | protected $references; | |
32 | ||
33 | /** | |
34 | * Creates entities from a JSON data set | |
35 | * | |
36 | * @param $path | |
37 | */ | |
38 | protected function loadDataSet($path) { | |
39 | if (!file_exists($path)) { | |
40 | $path = __DIR__ . '/../DataSets/' . $path . '.json'; | |
41 | } | |
42 | ||
43 | $dataSet = json_decode(file_get_contents($path), TRUE); | |
44 | foreach ($dataSet as $entityName => $entities) { | |
45 | foreach ($entities as $entityValues) { | |
46 | ||
47 | $entityValues = $this->replaceReferences($entityValues); | |
48 | ||
49 | $params = ['values' => $entityValues, 'checkPermissions' => FALSE]; | |
50 | $result = civicrm_api4($entityName, 'create', $params); | |
51 | if (isset($entityValues['@ref'])) { | |
52 | $this->references[$entityValues['@ref']] = $result->first(); | |
53 | } | |
54 | } | |
55 | } | |
56 | } | |
57 | ||
58 | /** | |
59 | * @param $name | |
60 | * | |
61 | * @return null|mixed | |
62 | */ | |
63 | protected function getReference($name) { | |
511e9a21 | 64 | return $this->references[$name] ?? NULL; |
19b53e5b C |
65 | } |
66 | ||
67 | /** | |
68 | * @param array $entityValues | |
69 | * | |
70 | * @return array | |
71 | */ | |
72 | private function replaceReferences($entityValues) { | |
73 | foreach ($entityValues as $name => $value) { | |
74 | if (is_array($value)) { | |
75 | $entityValues[$name] = $this->replaceReferences($value); | |
76 | } | |
77 | elseif (substr($value, 0, 4) === '@ref') { | |
78 | $referenceName = substr($value, 5); | |
79 | list ($reference, $property) = explode('.', $referenceName); | |
80 | $entityValues[$name] = $this->references[$reference][$property]; | |
81 | } | |
82 | } | |
83 | return $entityValues; | |
84 | } | |
85 | ||
86 | } |