BlueprintSchema.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. <?php
  2. /**
  3. * @package Grav\Common\Data
  4. *
  5. * @copyright Copyright (C) 2015 - 2019 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common\Data;
  9. use Grav\Common\Grav;
  10. use RocketTheme\Toolbox\ArrayTraits\Export;
  11. use RocketTheme\Toolbox\ArrayTraits\ExportInterface;
  12. use RocketTheme\Toolbox\Blueprints\BlueprintSchema as BlueprintSchemaBase;
  13. class BlueprintSchema extends BlueprintSchemaBase implements ExportInterface
  14. {
  15. use Export;
  16. protected $ignoreFormKeys = [
  17. 'title' => true,
  18. 'help' => true,
  19. 'placeholder' => true,
  20. 'placeholder_key' => true,
  21. 'placeholder_value' => true,
  22. 'fields' => true
  23. ];
  24. /**
  25. * @return array
  26. */
  27. public function getTypes()
  28. {
  29. return $this->types;
  30. }
  31. /**
  32. * @param string $name
  33. * @return array
  34. */
  35. public function getType($name)
  36. {
  37. return $this->types[$name] ?? [];
  38. }
  39. /**
  40. * Validate data against blueprints.
  41. *
  42. * @param array $data
  43. * @throws \RuntimeException
  44. */
  45. public function validate(array $data)
  46. {
  47. try {
  48. $messages = $this->validateArray($data, $this->nested, $this->items['']['form'] ?? []);
  49. } catch (\RuntimeException $e) {
  50. throw (new ValidationException($e->getMessage(), $e->getCode(), $e))->setMessages();
  51. }
  52. if (!empty($messages)) {
  53. throw (new ValidationException())->setMessages($messages);
  54. }
  55. }
  56. /**
  57. * @param array $data
  58. * @param array $toggles
  59. * @return array
  60. */
  61. public function processForm(array $data, array $toggles = [])
  62. {
  63. return $this->processFormRecursive($data, $toggles, $this->nested);
  64. }
  65. /**
  66. * Filter data by using blueprints.
  67. *
  68. * @param array $data Incoming data, for example from a form.
  69. * @param bool $missingValuesAsNull Include missing values as nulls.
  70. * @param bool $keepEmptyValues Include empty values.
  71. * @return array
  72. */
  73. public function filter(array $data, $missingValuesAsNull = false, $keepEmptyValues = false)
  74. {
  75. return $this->filterArray($data, $this->nested, $missingValuesAsNull, $keepEmptyValues);
  76. }
  77. /**
  78. * Flatten data by using blueprints.
  79. *
  80. * @param array $data Data to be flattened.
  81. * @return array
  82. */
  83. public function flattenData(array $data)
  84. {
  85. return $this->flattenArray($data, $this->nested, '');
  86. }
  87. /**
  88. * @param array $data
  89. * @param array $rules
  90. * @param string $prefix
  91. * @return array
  92. */
  93. protected function flattenArray(array $data, array $rules, string $prefix)
  94. {
  95. $array = [];
  96. foreach ($data as $key => $field) {
  97. $val = $rules[$key] ?? $rules['*'] ?? null;
  98. $rule = is_string($val) ? $this->items[$val] : null;
  99. if ($rule || isset($val['*'])) {
  100. // Item has been defined in blueprints.
  101. $array[$prefix.$key] = $field;
  102. } elseif (is_array($field) && is_array($val)) {
  103. // Array has been defined in blueprints.
  104. $array += $this->flattenArray($field, $val, $prefix . $key . '.');
  105. } else {
  106. // Undefined/extra item.
  107. $array[$prefix.$key] = $field;
  108. }
  109. }
  110. return $array;
  111. }
  112. /**
  113. * @param array $data
  114. * @param array $rules
  115. * @param array $parent
  116. * @return array
  117. * @throws \RuntimeException
  118. */
  119. protected function validateArray(array $data, array $rules, array $parent)
  120. {
  121. $messages = $this->checkRequired($data, $rules);
  122. foreach ($data as $key => $child) {
  123. $val = $rules[$key] ?? $rules['*'] ?? null;
  124. $rule = \is_string($val) ? $this->items[$val] : null;
  125. if ($rule) {
  126. // Item has been defined in blueprints.
  127. if (!empty($rule['disabled']) || !empty($rule['validate']['ignore'])) {
  128. // Skip validation in the ignored field.
  129. continue;
  130. }
  131. $messages += Validation::validate($child, $rule);
  132. } elseif (\is_array($child) && \is_array($val)) {
  133. // Array has been defined in blueprints.
  134. $messages += $this->validateArray($child, $val, $rule ?? []);
  135. } elseif (isset($parent['validation']) && $parent['validation'] === 'strict') {
  136. // Undefined/extra item.
  137. throw new \RuntimeException(sprintf('%s is not defined in blueprints', $key));
  138. }
  139. }
  140. return $messages;
  141. }
  142. /**
  143. * @param array $data
  144. * @param array $rules
  145. * @param bool $missingValuesAsNull
  146. * @param bool $keepEmptyValues
  147. * @return array
  148. */
  149. protected function filterArray(array $data, array $rules, $missingValuesAsNull, $keepEmptyValues)
  150. {
  151. $results = [];
  152. if ($missingValuesAsNull) {
  153. // First pass is to fill up all the fields with null. This is done to lock the ordering of the fields.
  154. foreach ($rules as $key => $rule) {
  155. if ($key && !isset($results[$key])) {
  156. $val = $rules[$key] ?? $rules['*'] ?? null;
  157. $rule = \is_string($val) ? $this->items[$val] : null;
  158. if (empty($rule['disabled']) && empty($rule['validate']['ignore'])) {
  159. continue;
  160. }
  161. }
  162. }
  163. }
  164. foreach ($data as $key => $field) {
  165. $val = $rules[$key] ?? $rules['*'] ?? null;
  166. $rule = \is_string($val) ? $this->items[$val] : null;
  167. if ($rule) {
  168. // Item has been defined in blueprints.
  169. if (!empty($rule['disabled']) || !empty($rule['validate']['ignore'])) {
  170. // Skip any data in the ignored field.
  171. unset($results[$key]);
  172. continue;
  173. }
  174. $field = Validation::filter($field, $rule);
  175. } elseif (\is_array($field) && \is_array($val)) {
  176. // Array has been defined in blueprints.
  177. $field = $this->filterArray($field, $val, $missingValuesAsNull, $keepEmptyValues);
  178. } elseif (isset($rules['validation']) && $rules['validation'] === 'strict') {
  179. // Skip any extra data.
  180. continue;
  181. }
  182. if ($keepEmptyValues || (null !== $field && (!\is_array($field) || !empty($field)))) {
  183. $results[$key] = $field;
  184. }
  185. }
  186. return $results ?: null;
  187. }
  188. /**
  189. * @param array|null $data
  190. * @param array $toggles
  191. * @param array $nested
  192. * @return array|null
  193. */
  194. protected function processFormRecursive(?array $data, array $toggles, array $nested)
  195. {
  196. foreach ($nested as $key => $value) {
  197. if ($key === '') {
  198. continue;
  199. }
  200. if ($key === '*') {
  201. // TODO: Add support to collections.
  202. continue;
  203. }
  204. if (is_array($value)) {
  205. // Recursively fetch the items.
  206. $data[$key] = $this->processFormRecursive($data[$key] ?? null, $toggles[$key] ?? [], $value);
  207. } else {
  208. $field = $this->get($value);
  209. // Do not add the field if:
  210. if (
  211. // Not an input field
  212. !$field
  213. // Field has been disabled
  214. || !empty($field['disabled'])
  215. // Field validation is set to be ignored
  216. || !empty($field['validate']['ignore'])
  217. // Field is toggleable and the toggle is turned off
  218. || (!empty($field['toggleable']) && empty($toggles[$key]))
  219. ) {
  220. continue;
  221. }
  222. if (!isset($data[$key])) {
  223. $data[$key] = null;
  224. }
  225. }
  226. }
  227. return $data;
  228. }
  229. /**
  230. * @param array $data
  231. * @param array $fields
  232. * @return array
  233. */
  234. protected function checkRequired(array $data, array $fields)
  235. {
  236. $messages = [];
  237. foreach ($fields as $name => $field) {
  238. if (!\is_string($field)) {
  239. continue;
  240. }
  241. $field = $this->items[$field];
  242. // Skip ignored field, it will not be required.
  243. if (!empty($field['disabled']) || !empty($field['validate']['ignore'])) {
  244. continue;
  245. }
  246. // Check if required.
  247. if (isset($field['validate']['required'])
  248. && $field['validate']['required'] === true) {
  249. if (isset($data[$name])) {
  250. continue;
  251. }
  252. if ($field['type'] === 'file' && isset($data['data']['name'][$name])) { //handle case of file input fields required
  253. continue;
  254. }
  255. $value = $field['label'] ?? $field['name'];
  256. $language = Grav::instance()['language'];
  257. $message = sprintf($language->translate('GRAV.FORM.MISSING_REQUIRED_FIELD', null, true) . ' %s', $language->translate($value));
  258. $messages[$field['name']][] = $message;
  259. }
  260. }
  261. return $messages;
  262. }
  263. /**
  264. * @param array $field
  265. * @param string $property
  266. * @param array $call
  267. */
  268. protected function dynamicConfig(array &$field, $property, array &$call)
  269. {
  270. $value = $call['params'];
  271. $default = $field[$property] ?? null;
  272. $config = Grav::instance()['config']->get($value, $default);
  273. if (null !== $config) {
  274. $field[$property] = $config;
  275. }
  276. }
  277. }