BlueprintSchema.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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);
  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. * @return array
  116. * @throws \RuntimeException
  117. */
  118. protected function validateArray(array $data, array $rules)
  119. {
  120. $messages = $this->checkRequired($data, $rules);
  121. foreach ($data as $key => $field) {
  122. $val = $rules[$key] ?? $rules['*'] ?? null;
  123. $rule = \is_string($val) ? $this->items[$val] : null;
  124. if ($rule) {
  125. // Item has been defined in blueprints.
  126. if (!empty($rule['disabled']) || !empty($rule['validate']['ignore'])) {
  127. // Skip validation in the ignored field.
  128. continue;
  129. }
  130. $messages += Validation::validate($field, $rule);
  131. } elseif (\is_array($field) && \is_array($val)) {
  132. // Array has been defined in blueprints.
  133. $messages += $this->validateArray($field, $val);
  134. } elseif (isset($rules['validation']) && $rules['validation'] === 'strict') {
  135. // Undefined/extra item.
  136. throw new \RuntimeException(sprintf('%s is not defined in blueprints', $key));
  137. }
  138. }
  139. return $messages;
  140. }
  141. /**
  142. * @param array $data
  143. * @param array $rules
  144. * @param bool $missingValuesAsNull
  145. * @param bool $keepEmptyValues
  146. * @return array
  147. */
  148. protected function filterArray(array $data, array $rules, $missingValuesAsNull, $keepEmptyValues)
  149. {
  150. $results = [];
  151. if ($missingValuesAsNull) {
  152. // First pass is to fill up all the fields with null. This is done to lock the ordering of the fields.
  153. foreach ($rules as $key => $rule) {
  154. if ($key && !isset($results[$key])) {
  155. $val = $rules[$key] ?? $rules['*'] ?? null;
  156. $rule = \is_string($val) ? $this->items[$val] : null;
  157. if (empty($rule['disabled']) && empty($rule['validate']['ignore'])) {
  158. continue;
  159. }
  160. }
  161. }
  162. }
  163. foreach ($data as $key => $field) {
  164. $val = $rules[$key] ?? $rules['*'] ?? null;
  165. $rule = \is_string($val) ? $this->items[$val] : null;
  166. if ($rule) {
  167. // Item has been defined in blueprints.
  168. if (!empty($rule['disabled']) || !empty($rule['validate']['ignore'])) {
  169. // Skip any data in the ignored field.
  170. unset($results[$key]);
  171. continue;
  172. }
  173. $field = Validation::filter($field, $rule);
  174. } elseif (\is_array($field) && \is_array($val)) {
  175. // Array has been defined in blueprints.
  176. $field = $this->filterArray($field, $val, $missingValuesAsNull, $keepEmptyValues);
  177. } elseif (isset($rules['validation']) && $rules['validation'] === 'strict') {
  178. // Skip any extra data.
  179. continue;
  180. }
  181. if ($keepEmptyValues || (null !== $field && (!\is_array($field) || !empty($field)))) {
  182. $results[$key] = $field;
  183. }
  184. }
  185. return $results ?: null;
  186. }
  187. /**
  188. * @param array|null $data
  189. * @param array $toggles
  190. * @param array $nested
  191. * @return array|null
  192. */
  193. protected function processFormRecursive(?array $data, array $toggles, array $nested)
  194. {
  195. foreach ($nested as $key => $value) {
  196. if ($key === '') {
  197. continue;
  198. }
  199. if ($key === '*') {
  200. // TODO: Add support to collections.
  201. continue;
  202. }
  203. if (is_array($value)) {
  204. // Recursively fetch the items.
  205. $data[$key] = $this->processFormRecursive($data[$key] ?? null, $toggles[$key] ?? [], $value);
  206. } else {
  207. $field = $this->get($value);
  208. // Do not add the field if:
  209. if (
  210. // Not an input field
  211. !$field
  212. // Field has been disabled
  213. || !empty($field['disabled'])
  214. // Field validation is set to be ignored
  215. || !empty($field['validate']['ignore'])
  216. // Field is toggleable and the toggle is turned off
  217. || (!empty($field['toggleable']) && empty($toggles[$key]))
  218. ) {
  219. continue;
  220. }
  221. if (!isset($data[$key])) {
  222. $data[$key] = null;
  223. }
  224. }
  225. }
  226. return $data;
  227. }
  228. /**
  229. * @param array $data
  230. * @param array $fields
  231. * @return array
  232. */
  233. protected function checkRequired(array $data, array $fields)
  234. {
  235. $messages = [];
  236. foreach ($fields as $name => $field) {
  237. if (!\is_string($field)) {
  238. continue;
  239. }
  240. $field = $this->items[$field];
  241. // Skip ignored field, it will not be required.
  242. if (!empty($field['disabled']) || !empty($field['validate']['ignore'])) {
  243. continue;
  244. }
  245. // Check if required.
  246. if (isset($field['validate']['required'])
  247. && $field['validate']['required'] === true) {
  248. if (isset($data[$name])) {
  249. continue;
  250. }
  251. if ($field['type'] === 'file' && isset($data['data']['name'][$name])) { //handle case of file input fields required
  252. continue;
  253. }
  254. $value = $field['label'] ?? $field['name'];
  255. $language = Grav::instance()['language'];
  256. $message = sprintf($language->translate('GRAV.FORM.MISSING_REQUIRED_FIELD', null, true) . ' %s', $language->translate($value));
  257. $messages[$field['name']][] = $message;
  258. }
  259. }
  260. return $messages;
  261. }
  262. /**
  263. * @param array $field
  264. * @param string $property
  265. * @param array $call
  266. */
  267. protected function dynamicConfig(array &$field, $property, array &$call)
  268. {
  269. $value = $call['params'];
  270. $default = $field[$property] ?? null;
  271. $config = Grav::instance()['config']->get($value, $default);
  272. if (null !== $config) {
  273. $field[$property] = $config;
  274. }
  275. }
  276. }