Merge pull request #19936 from jmcclelland/only-include-completed
[civicrm-core.git] / tests / phpunit / api / v4 / Traits / TestDataLoaderTrait.php
1 <?php
2
3 /*
4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
6 | |
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 |
10 +--------------------------------------------------------------------+
11 */
12
13 /**
14 *
15 * @package CRM
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 */
18
19
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) {
64 return $this->references[$name] ?? NULL;
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 }