Rename `<af-model>` to `<af-entity>` to better match API terminology
[civicrm-core.git] / ext / afform / core / Civi / Afform / Utils.php
CommitLineData
3fe34185
CW
1<?php
2
3namespace Civi\Afform;
4
5class Utils {
6
7 /**
8 * Gets entity metadata and all fields from the form
9 *
10 * @param array $layout
11 * @return array
12 */
13 public static function getEntities($layout) {
c37151d2 14 $entities = array_column(self::getTags($layout, 'af-entity'), NULL, 'name');
3fe34185
CW
15 self::getFields($layout, $entities);
16 return $entities;
17 }
18
19 /**
c37151d2 20 * Returns all tags with a certain tag name, e.g. 'af-entity'
3fe34185
CW
21 *
22 * @param array $collection
23 * @param string $tagName
24 * @return array
25 */
26 public static function getTags($collection, $tagName) {
27 $results = [];
28 if ($collection['#tag'] == $tagName) {
29 $results[] = self::getProps($collection);
30 }
31 foreach ($collection['#children'] ?? [] as $child) {
32 $results = array_merge($results, self::getTags($child, $tagName));
33 }
34 return $results;
35 }
36
37 /**
38 * @param array $layout
39 * @param array $entities
40 */
41 protected static function getFields($layout, &$entities) {
42 foreach ($layout['#children'] as $child) {
dce8ad72 43 if ($child['#tag'] == 'af-fieldset' && !empty($child['#children'])) {
8410442c 44 $entities[$child['model']]['fields'] = array_merge($entities[$child['model']]['fields'] ?? [], self::getTags($child, 'af-field'));
3fe34185
CW
45 }
46 elseif (!empty($child['#children'])) {
47 self::getFields($child['#children'], $entities);
48 }
49 }
50 }
51
52 /**
53 * Returns all the real properties of a collection,
54 * filtering out any array keys that start with a hashtag
55 *
56 * @param array $collection
57 * @return array
58 */
59 public static function getProps($collection) {
60 return array_filter($collection, function($key) {
61 return substr($key, 0, 1) !== '#';
62 }, ARRAY_FILTER_USE_KEY);
63 }
64
65}