BlueprintSchema.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. <?php
  2. namespace RocketTheme\Toolbox\Blueprints;
  3. /**
  4. * BlueprintSchema is used to define a data structure.
  5. *
  6. * @package RocketTheme\Toolbox\Blueprints
  7. * @author RocketTheme
  8. * @license MIT
  9. */
  10. class BlueprintSchema
  11. {
  12. /**
  13. * @var array
  14. */
  15. protected $items = [];
  16. /**
  17. * @var array
  18. */
  19. protected $rules = [];
  20. /**
  21. * @var array
  22. */
  23. protected $nested = [];
  24. /**
  25. * @var array
  26. */
  27. protected $dynamic = [];
  28. /**
  29. * @var array
  30. */
  31. protected $filter = ['validation' => true];
  32. /**
  33. * @var array
  34. */
  35. protected $ignoreFormKeys = ['fields' => 1];
  36. /**
  37. * @var array
  38. */
  39. protected $types = [];
  40. /**
  41. * Constructor.
  42. *
  43. * @param array $serialized Serialized content if available.
  44. */
  45. public function __construct($serialized = null)
  46. {
  47. if (is_array($serialized) && !empty($serialized)) {
  48. $this->items = (array) $serialized['items'];
  49. $this->rules = (array) $serialized['rules'];
  50. $this->nested = (array) $serialized['nested'];
  51. $this->dynamic = (array) $serialized['dynamic'];
  52. $this->filter = (array) $serialized['filter'];
  53. }
  54. }
  55. /**
  56. * @param array $types
  57. * @return $this
  58. */
  59. public function setTypes(array $types)
  60. {
  61. $this->types = $types;
  62. return $this;
  63. }
  64. /**
  65. * Restore Blueprints object.
  66. *
  67. * @param array $serialized
  68. * @return static
  69. */
  70. public static function restore(array $serialized)
  71. {
  72. return new static($serialized);
  73. }
  74. /**
  75. * Initialize blueprints with its dynamic fields.
  76. *
  77. * @return $this
  78. */
  79. public function init()
  80. {
  81. foreach ($this->dynamic as $key => $data) {
  82. $field = &$this->items[$key];
  83. foreach ($data as $property => $call) {
  84. $action = 'dynamic' . ucfirst($call['action']);
  85. if (method_exists($this, $action)) {
  86. $this->{$action}($field, $property, $call);
  87. }
  88. }
  89. }
  90. return $this;
  91. }
  92. /**
  93. * Set filter for inherited properties.
  94. *
  95. * @param array $filter List of field names to be inherited.
  96. */
  97. public function setFilter(array $filter)
  98. {
  99. $this->filter = array_flip($filter);
  100. }
  101. /**
  102. * Get value by using dot notation for nested arrays/objects.
  103. *
  104. * @example $value = $data->get('this.is.my.nested.variable');
  105. *
  106. * @param string $name Dot separated path to the requested value.
  107. * @param mixed $default Default value (or null).
  108. * @param string $separator Separator, defaults to '.'
  109. *
  110. * @return mixed Value.
  111. */
  112. public function get($name, $default = null, $separator = '.')
  113. {
  114. $name = $separator != '.' ? strtr($name, $separator, '.') : $name;
  115. return isset($this->items[$name]) ? $this->items[$name] : $default;
  116. }
  117. /**
  118. * Set value by using dot notation for nested arrays/objects.
  119. *
  120. * @example $value = $data->set('this.is.my.nested.variable', $newField);
  121. *
  122. * @param string $name Dot separated path to the requested value.
  123. * @param mixed $value New value.
  124. * @param string $separator Separator, defaults to '.'
  125. */
  126. public function set($name, $value, $separator = '.')
  127. {
  128. $name = $separator != '.' ? strtr($name, $separator, '.') : $name;
  129. $this->items[$name] = $value;
  130. $this->addProperty($name);
  131. }
  132. /**
  133. * Define value by using dot notation for nested arrays/objects.
  134. *
  135. * @example $value = $data->set('this.is.my.nested.variable', true);
  136. *
  137. * @param string $name Dot separated path to the requested value.
  138. * @param mixed $value New value.
  139. * @param string $separator Separator, defaults to '.'
  140. */
  141. public function def($name, $value, $separator = '.')
  142. {
  143. $this->set($name, $this->get($name, $value, $separator), $separator);
  144. }
  145. /**
  146. * @return array
  147. * @deprecated
  148. */
  149. public function toArray()
  150. {
  151. return $this->getState();
  152. }
  153. /**
  154. * Convert object into an array.
  155. *
  156. * @return array
  157. */
  158. public function getState()
  159. {
  160. return [
  161. 'items' => $this->items,
  162. 'rules' => $this->rules,
  163. 'nested' => $this->nested,
  164. 'dynamic' => $this->dynamic,
  165. 'filter' => $this->filter
  166. ];
  167. }
  168. /**
  169. * Get nested structure containing default values defined in the blueprints.
  170. *
  171. * Fields without default value are ignored in the list.
  172. *
  173. * @return array
  174. */
  175. public function getDefaults()
  176. {
  177. return $this->buildDefaults($this->nested);
  178. }
  179. /**
  180. * Embed an array to the blueprint.
  181. *
  182. * @param $name
  183. * @param array $value
  184. * @param string $separator
  185. * @param bool $merge Merge fields instead replacing them.
  186. * @return $this
  187. */
  188. public function embed($name, array $value, $separator = '.', $merge = false)
  189. {
  190. if (isset($value['rules'])) {
  191. $this->rules = array_merge($this->rules, $value['rules']);
  192. }
  193. $name = $separator != '.' ? strtr($name, $separator, '.') : $name;
  194. if (isset($value['form'])) {
  195. $form = array_diff_key($value['form'], ['fields' => 1, 'field' => 1]);
  196. } else {
  197. $form = [];
  198. }
  199. $items = isset($this->items[$name]) ? $this->items[$name] : ['type' => '_root', 'form_field' => false];
  200. $this->items[$name] = $items;
  201. $this->addProperty($name);
  202. $prefix = $name ? $name . '.' : '';
  203. $params = array_intersect_key($form, $this->filter);
  204. $location = [$name];
  205. if (isset($value['form']['field'])) {
  206. $this->parseFormField($name, $value['form']['field'], $params, $prefix, '', $merge, $location);
  207. } elseif (isset($value['form']['fields'])) {
  208. $this->parseFormFields($value['form']['fields'], $params, $prefix, '', $merge, $location);
  209. }
  210. $this->items[$name] += ['form' => $form];
  211. return $this;
  212. }
  213. /**
  214. * Merge two arrays by using blueprints.
  215. *
  216. * @param array $data1
  217. * @param array $data2
  218. * @param string $name Optional
  219. * @param string $separator Optional
  220. * @return array
  221. */
  222. public function mergeData(array $data1, array $data2, $name = null, $separator = '.')
  223. {
  224. $nested = $this->getNested($name, $separator);
  225. if (!is_array($nested)) {
  226. $nested = [];
  227. }
  228. return $this->mergeArrays($data1, $data2, $nested);
  229. }
  230. /**
  231. * Get the property with given path.
  232. *
  233. * @param string $path
  234. * @param string $separator
  235. * @return mixed
  236. */
  237. public function getProperty($path = null, $separator = '.')
  238. {
  239. $name = $this->getPropertyName($path, $separator);
  240. $property = $this->get($name);
  241. $nested = $this->getNested($name);
  242. return $this->getPropertyRecursion($property, $nested);
  243. }
  244. /**
  245. * Returns name of the property with given path.
  246. *
  247. * @param string $path
  248. * @param string $separator
  249. * @return string
  250. */
  251. public function getPropertyName($path = null, $separator = '.')
  252. {
  253. $parts = explode($separator, $path);
  254. $nested = $this->nested;
  255. $result = [];
  256. while (($part = array_shift($parts)) !== null) {
  257. if (!isset($nested[$part])) {
  258. if (isset($nested['*'])) {
  259. $part = '*';
  260. } else {
  261. return implode($separator, array_merge($result, [$part], $parts));
  262. }
  263. }
  264. $result[] = $part;
  265. $nested = $nested[$part];
  266. }
  267. return implode('.', $result);
  268. }
  269. /**
  270. * Return data fields that do not exist in blueprints.
  271. *
  272. * @param array $data
  273. * @param string $prefix
  274. * @return array
  275. */
  276. public function extra(array $data, $prefix = '')
  277. {
  278. $rules = $this->nested;
  279. // Drill down to prefix level
  280. if (!empty($prefix)) {
  281. $parts = explode('.', trim($prefix, '.'));
  282. foreach ($parts as $part) {
  283. $rules = isset($rules[$part]) ? $rules[$part] : [];
  284. }
  285. }
  286. // Check if the form cannot have extra fields.
  287. if (isset($rules[''])) {
  288. $rule = $this->items[''];
  289. if (isset($rule['type']) && $rule['type'] != '_root') {
  290. return [];
  291. }
  292. }
  293. return $this->extraArray($data, $rules, $prefix);
  294. }
  295. /**
  296. * Get the property with given path.
  297. *
  298. * @param $property
  299. * @param $nested
  300. * @return mixed
  301. */
  302. protected function getPropertyRecursion($property, $nested)
  303. {
  304. if (!isset($property['type']) || empty($nested) || !is_array($nested)) {
  305. return $property;
  306. }
  307. if ($property['type'] === '_root') {
  308. foreach ($nested as $key => $value) {
  309. if ($key === '') {
  310. continue;
  311. }
  312. $name = is_array($value) ? $key : $value;
  313. $property['fields'][$key] = $this->getPropertyRecursion($this->get($name), $value);
  314. }
  315. } elseif ($property['type'] === '_parent' || !empty($property['array'])) {
  316. foreach ($nested as $key => $value) {
  317. $name = is_array($value) ? "{$property['name']}.{$key}" : $value;
  318. $property['fields'][$key] = $this->getPropertyRecursion($this->get($name), $value);
  319. }
  320. }
  321. return $property;
  322. }
  323. /**
  324. * Get property from the definition.
  325. *
  326. * @param string $path Comma separated path to the property.
  327. * @param string $separator
  328. * @return array|string|null
  329. * @internal
  330. */
  331. protected function getNested($path = null, $separator = '.')
  332. {
  333. if (!$path) {
  334. return $this->nested;
  335. }
  336. $parts = explode($separator, $path);
  337. $item = array_pop($parts);
  338. $nested = $this->nested;
  339. foreach ($parts as $part) {
  340. if (!isset($nested[$part])) {
  341. $part = '*';
  342. if (!isset($nested[$part])) {
  343. return [];
  344. }
  345. }
  346. $nested = $nested[$part];
  347. }
  348. return isset($nested[$item]) ? $nested[$item] : (isset($nested['*']) ? $nested['*'] : null);
  349. }
  350. /**
  351. * @param array $nested
  352. * @return array
  353. */
  354. protected function buildDefaults(array $nested)
  355. {
  356. $defaults = [];
  357. foreach ($nested as $key => $value) {
  358. if ($key === '*') {
  359. // TODO: Add support for adding defaults to collections.
  360. continue;
  361. }
  362. if (is_array($value)) {
  363. // Recursively fetch the items.
  364. $list = $this->buildDefaults($value);
  365. // Only return defaults if there are any.
  366. if (!empty($list)) {
  367. $defaults[$key] = $list;
  368. }
  369. } else {
  370. // We hit a field; get default from it if it exists.
  371. $item = $this->get($value);
  372. // Only return default value if it exists.
  373. if (isset($item['default'])) {
  374. $defaults[$key] = $item['default'];
  375. }
  376. }
  377. }
  378. return $defaults;
  379. }
  380. /**
  381. * @param array $data1
  382. * @param array $data2
  383. * @param array $rules
  384. * @return array
  385. * @internal
  386. */
  387. protected function mergeArrays(array $data1, array $data2, array $rules)
  388. {
  389. foreach ($data2 as $key => $field) {
  390. $val = isset($rules[$key]) ? $rules[$key] : null;
  391. $rule = is_string($val) ? $this->items[$val] : null;
  392. if (!empty($rule['type']) && $rule['type'][0] === '_'
  393. || (array_key_exists($key, $data1) && is_array($data1[$key]) && is_array($field) && is_array($val) && !isset($val['*']))
  394. ) {
  395. // Array has been defined in blueprints and is not a collection of items.
  396. $data1[$key] = $this->mergeArrays($data1[$key], $field, $val);
  397. } else {
  398. // Otherwise just take value from the data2.
  399. $data1[$key] = $field;
  400. }
  401. }
  402. return $data1;
  403. }
  404. /**
  405. * Gets all field definitions from the blueprints.
  406. *
  407. * @param array $fields Fields to parse.
  408. * @param array $params Property parameters.
  409. * @param string $prefix Property prefix.
  410. * @param string $parent Parent property.
  411. * @param bool $merge Merge fields instead replacing them.
  412. * @param array $formPath
  413. */
  414. protected function parseFormFields(array $fields, array $params, $prefix = '', $parent = '', $merge = false, array $formPath = [])
  415. {
  416. if (isset($fields['type']) && !is_array($fields['type'])) {
  417. return;
  418. }
  419. // Go though all the fields in current level.
  420. foreach ($fields as $key => $field) {
  421. $this->parseFormField($key, $field, $params, $prefix, $parent, $merge, $formPath);
  422. }
  423. }
  424. /**
  425. * @param string $key
  426. * @param array $field
  427. * @param array $params
  428. * @param string $prefix
  429. * @param string $parent
  430. * @param bool $merge
  431. * @param array $formPath
  432. */
  433. protected function parseFormField($key, array $field, array $params, $prefix = '', $parent = '', $merge = false, array $formPath = [])
  434. {
  435. // Skip illegal field (needs to be an array).
  436. if (!is_array($field)) {
  437. return;
  438. }
  439. $key = $this->getFieldKey($key, $prefix, $parent);
  440. $newPath = array_merge($formPath, [$key]);
  441. $properties = array_diff_key($field, $this->ignoreFormKeys) + $params;
  442. $properties['name'] = $key;
  443. // Set default properties for the field type.
  444. $type = isset($properties['type']) ? $properties['type'] : '';
  445. if (isset($this->types[$type])) {
  446. $properties += $this->types[$type];
  447. }
  448. // Merge properties with existing ones.
  449. if ($merge && isset($this->items[$key])) {
  450. $properties += $this->items[$key];
  451. }
  452. $isInputField = !isset($properties['input@']) || $properties['input@'];
  453. if (!$isInputField) {
  454. // Remove property if it exists.
  455. if (isset($this->items[$key])) {
  456. $this->removeProperty($key);
  457. }
  458. } elseif (!isset($this->items[$key])) {
  459. // Add missing property.
  460. $this->addProperty($key);
  461. }
  462. if (isset($field['fields'])) {
  463. // Recursively get all the nested fields.
  464. $isArray = !empty($properties['array']);
  465. $newParams = array_intersect_key($properties, $this->filter);
  466. $this->parseFormFields($field['fields'], $newParams, $prefix, $key . ($isArray ? '.*': ''), $merge, $newPath);
  467. } else {
  468. if (!isset($this->items[$key])) {
  469. // Add parent rules.
  470. $path = explode('.', $key);
  471. array_pop($path);
  472. $parent = '';
  473. foreach ($path as $part) {
  474. $parent .= ($parent ? '.' : '') . $part;
  475. if (!isset($this->items[$parent])) {
  476. $this->items[$parent] = ['type' => '_parent', 'name' => $parent, 'form_field' => false];
  477. }
  478. }
  479. }
  480. if ($isInputField) {
  481. $this->parseProperties($key, $properties);
  482. }
  483. }
  484. if ($isInputField) {
  485. $this->items[$key] = $properties;
  486. }
  487. }
  488. protected function getFieldKey($key, $prefix, $parent)
  489. {
  490. // Set name from the array key.
  491. if ($key && $key[0] == '.') {
  492. return ($parent ?: rtrim($prefix, '.')) . $key;
  493. }
  494. return $prefix . $key;
  495. }
  496. protected function parseProperties($key, array &$properties)
  497. {
  498. $key = ltrim($key, '.');
  499. if (!empty($properties['data'])) {
  500. $this->dynamic[$key] = $properties['data'];
  501. }
  502. foreach ($properties as $name => $value) {
  503. if (!empty($name) && ($name[0] === '@' || $name[strlen($name) - 1] === '@')) {
  504. $list = explode('-', trim($name, '@'), 2);
  505. $action = array_shift($list);
  506. $property = array_shift($list);
  507. $this->dynamic[$key][$property] = ['action' => $action, 'params' => $value];
  508. }
  509. }
  510. // Initialize predefined validation rule.
  511. if (isset($properties['validate']['rule'])) {
  512. $properties['validate'] += $this->getRule($properties['validate']['rule']);
  513. }
  514. }
  515. /**
  516. * Add property to the definition.
  517. *
  518. * @param string $path Comma separated path to the property.
  519. * @internal
  520. */
  521. protected function addProperty($path)
  522. {
  523. $parts = explode('.', $path);
  524. $item = array_pop($parts);
  525. $nested = &$this->nested;
  526. foreach ($parts as $part) {
  527. if (!isset($nested[$part]) || !is_array($nested[$part])) {
  528. $nested[$part] = [];
  529. }
  530. $nested = &$nested[$part];
  531. }
  532. if (!isset($nested[$item])) {
  533. $nested[$item] = $path;
  534. }
  535. }
  536. /**
  537. * Remove property to the definition.
  538. *
  539. * @param string $path Comma separated path to the property.
  540. * @internal
  541. */
  542. protected function removeProperty($path)
  543. {
  544. $parts = explode('.', $path);
  545. $item = array_pop($parts);
  546. $nested = &$this->nested;
  547. foreach ($parts as $part) {
  548. if (!isset($nested[$part]) || !is_array($nested[$part])) {
  549. return;
  550. }
  551. $nested = &$nested[$part];
  552. }
  553. if (isset($nested[$item])) {
  554. unset($nested[$item]);
  555. }
  556. }
  557. /**
  558. * @param $rule
  559. * @return array
  560. * @internal
  561. */
  562. protected function getRule($rule)
  563. {
  564. if (isset($this->rules[$rule]) && is_array($this->rules[$rule])) {
  565. return $this->rules[$rule];
  566. }
  567. return [];
  568. }
  569. /**
  570. * @param array $data
  571. * @param array $rules
  572. * @param string $prefix
  573. * @return array
  574. * @internal
  575. */
  576. protected function extraArray(array $data, array $rules, $prefix)
  577. {
  578. $array = [];
  579. foreach ($data as $key => $field) {
  580. $val = isset($rules[$key]) ? $rules[$key] : (isset($rules['*']) ? $rules['*'] : null);
  581. $rule = is_string($val) ? $this->items[$val] : null;
  582. if ($rule || isset($val['*'])) {
  583. // Item has been defined in blueprints.
  584. } elseif (is_array($field) && is_array($val)) {
  585. // Array has been defined in blueprints.
  586. $array += $this->ExtraArray($field, $val, $prefix . $key . '.');
  587. } else {
  588. // Undefined/extra item.
  589. $array[$prefix.$key] = $field;
  590. }
  591. }
  592. return $array;
  593. }
  594. /**
  595. * @param array $field
  596. * @param string $property
  597. * @param array $call
  598. */
  599. protected function dynamicData(array &$field, $property, array $call)
  600. {
  601. $params = $call['params'];
  602. if (is_array($params)) {
  603. $function = array_shift($params);
  604. } else {
  605. $function = $params;
  606. $params = [];
  607. }
  608. $list = preg_split('/::/', $function, 2);
  609. $f = array_pop($list);
  610. $o = array_pop($list);
  611. if (!$o) {
  612. if (function_exists($f)) {
  613. $data = call_user_func_array($f, $params);
  614. }
  615. } else {
  616. if (method_exists($o, $f)) {
  617. $data = call_user_func_array(array($o, $f), $params);
  618. }
  619. }
  620. // If function returns a value,
  621. if (isset($data)) {
  622. if (isset($field[$property]) && is_array($field[$property]) && is_array($data)) {
  623. // Combine field and @data-field together.
  624. $field[$property] += $data;
  625. } else {
  626. // Or create/replace field with @data-field.
  627. $field[$property] = $data;
  628. }
  629. }
  630. }
  631. }