BlueprintSchema.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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 (empty($nested) || !is_array($nested) || !isset($property['type'])) {
  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 ((array_key_exists($key, $data1) && is_array($data1[$key]) && is_array($field) && is_array($val) && !isset($val['*']))
  393. || (!empty($rule['type']) && $rule['type'][0] === '_')) {
  394. // Array has been defined in blueprints and is not a collection of items.
  395. $data1[$key] = $this->mergeArrays($data1[$key], $field, $val);
  396. } else {
  397. // Otherwise just take value from the data2.
  398. $data1[$key] = $field;
  399. }
  400. }
  401. return $data1;
  402. }
  403. /**
  404. * Gets all field definitions from the blueprints.
  405. *
  406. * @param array $fields Fields to parse.
  407. * @param array $params Property parameters.
  408. * @param string $prefix Property prefix.
  409. * @param string $parent Parent property.
  410. * @param bool $merge Merge fields instead replacing them.
  411. * @param array $formPath
  412. */
  413. protected function parseFormFields(array $fields, array $params, $prefix = '', $parent = '', $merge = false, array $formPath = [])
  414. {
  415. if (isset($fields['type']) && !is_array($fields['type'])) {
  416. return;
  417. }
  418. // Go though all the fields in current level.
  419. foreach ($fields as $key => $field) {
  420. $this->parseFormField($key, $field, $params, $prefix, $parent, $merge, $formPath);
  421. }
  422. }
  423. /**
  424. * @param string $key
  425. * @param array $field
  426. * @param array $params
  427. * @param string $prefix
  428. * @param string $parent
  429. * @param bool $merge
  430. * @param array $formPath
  431. */
  432. protected function parseFormField($key, array $field, array $params, $prefix = '', $parent = '', $merge = false, array $formPath = [])
  433. {
  434. // Skip illegal field (needs to be an array).
  435. if (!is_array($field)) {
  436. return;
  437. }
  438. $key = $this->getFieldKey($key, $prefix, $parent);
  439. $newPath = array_merge($formPath, [$key]);
  440. $properties = array_diff_key($field, $this->ignoreFormKeys) + $params;
  441. $properties['name'] = $key;
  442. // Set default properties for the field type.
  443. $type = isset($properties['type']) ? $properties['type'] : '';
  444. if (isset($this->types[$type])) {
  445. $properties += $this->types[$type];
  446. }
  447. // Merge properties with existing ones.
  448. if ($merge && isset($this->items[$key])) {
  449. $properties += $this->items[$key];
  450. }
  451. $isInputField = !isset($properties['input@']) || $properties['input@'];
  452. if (!$isInputField) {
  453. // Remove property if it exists.
  454. if (isset($this->items[$key])) {
  455. $this->removeProperty($key);
  456. }
  457. } elseif (!isset($this->items[$key])) {
  458. // Add missing property.
  459. $this->addProperty($key);
  460. }
  461. if (isset($field['fields'])) {
  462. // Recursively get all the nested fields.
  463. $isArray = !empty($properties['array']);
  464. $newParams = array_intersect_key($properties, $this->filter);
  465. $this->parseFormFields($field['fields'], $newParams, $prefix, $key . ($isArray ? '.*': ''), $merge, $newPath);
  466. } else {
  467. if (!isset($this->items[$key])) {
  468. // Add parent rules.
  469. $path = explode('.', $key);
  470. array_pop($path);
  471. $parent = '';
  472. foreach ($path as $part) {
  473. $parent .= ($parent ? '.' : '') . $part;
  474. if (!isset($this->items[$parent])) {
  475. $this->items[$parent] = ['type' => '_parent', 'name' => $parent, 'form_field' => false];
  476. }
  477. }
  478. }
  479. if ($isInputField) {
  480. $this->parseProperties($key, $properties);
  481. }
  482. }
  483. if ($isInputField) {
  484. $this->items[$key] = $properties;
  485. }
  486. }
  487. protected function getFieldKey($key, $prefix, $parent)
  488. {
  489. // Set name from the array key.
  490. if ($key && $key[0] === '.') {
  491. return ($parent ?: rtrim($prefix, '.')) . $key;
  492. }
  493. return $prefix . $key;
  494. }
  495. protected function parseProperties($key, array &$properties)
  496. {
  497. $key = ltrim($key, '.');
  498. if (!empty($properties['data'])) {
  499. $this->dynamic[$key] = $properties['data'];
  500. }
  501. foreach ($properties as $name => $value) {
  502. if (!empty($name) && ($name[0] === '@' || $name[strlen($name) - 1] === '@')) {
  503. $list = explode('-', trim($name, '@'), 2);
  504. $action = array_shift($list);
  505. $property = array_shift($list);
  506. $this->dynamic[$key][$property] = ['action' => $action, 'params' => $value];
  507. }
  508. }
  509. // Initialize predefined validation rule.
  510. if (isset($properties['validate']['rule'])) {
  511. $properties['validate'] += $this->getRule($properties['validate']['rule']);
  512. }
  513. }
  514. /**
  515. * Add property to the definition.
  516. *
  517. * @param string $path Comma separated path to the property.
  518. * @internal
  519. */
  520. protected function addProperty($path)
  521. {
  522. $parts = explode('.', $path);
  523. $item = array_pop($parts);
  524. $nested = &$this->nested;
  525. foreach ($parts as $part) {
  526. if (!isset($nested[$part]) || !is_array($nested[$part])) {
  527. $nested[$part] = [];
  528. }
  529. $nested = &$nested[$part];
  530. }
  531. if (!isset($nested[$item])) {
  532. $nested[$item] = $path;
  533. }
  534. }
  535. /**
  536. * Remove property to the definition.
  537. *
  538. * @param string $path Comma separated path to the property.
  539. * @internal
  540. */
  541. protected function removeProperty($path)
  542. {
  543. $parts = explode('.', $path);
  544. $item = array_pop($parts);
  545. $nested = &$this->nested;
  546. foreach ($parts as $part) {
  547. if (!isset($nested[$part]) || !is_array($nested[$part])) {
  548. return;
  549. }
  550. $nested = &$nested[$part];
  551. }
  552. if (isset($nested[$item])) {
  553. unset($nested[$item]);
  554. }
  555. }
  556. /**
  557. * @param $rule
  558. * @return array
  559. * @internal
  560. */
  561. protected function getRule($rule)
  562. {
  563. if (isset($this->rules[$rule]) && is_array($this->rules[$rule])) {
  564. return $this->rules[$rule];
  565. }
  566. return [];
  567. }
  568. /**
  569. * @param array $data
  570. * @param array $rules
  571. * @param string $prefix
  572. * @return array
  573. * @internal
  574. */
  575. protected function extraArray(array $data, array $rules, $prefix)
  576. {
  577. $array = [];
  578. foreach ($data as $key => $field) {
  579. $val = isset($rules[$key]) ? $rules[$key] : (isset($rules['*']) ? $rules['*'] : null);
  580. $rule = is_string($val) ? $this->items[$val] : null;
  581. if ($rule || isset($val['*'])) {
  582. // Item has been defined in blueprints.
  583. } elseif (is_array($field) && is_array($val)) {
  584. // Array has been defined in blueprints.
  585. $array += $this->extraArray($field, $val, $prefix . $key . '.');
  586. } else {
  587. // Undefined/extra item.
  588. $array[$prefix.$key] = $field;
  589. }
  590. }
  591. return $array;
  592. }
  593. /**
  594. * @param array $field
  595. * @param string $property
  596. * @param array $call
  597. */
  598. protected function dynamicData(array &$field, $property, array $call)
  599. {
  600. $params = $call['params'];
  601. if (is_array($params)) {
  602. $function = array_shift($params);
  603. } else {
  604. $function = $params;
  605. $params = [];
  606. }
  607. $list = explode('::', $function, 2);
  608. $f = array_pop($list);
  609. $o = array_pop($list);
  610. if (!$o) {
  611. if (function_exists($f)) {
  612. $data = call_user_func_array($f, $params);
  613. }
  614. } else {
  615. if (method_exists($o, $f)) {
  616. $data = call_user_func_array(array($o, $f), $params);
  617. }
  618. }
  619. // If function returns a value,
  620. if (isset($data)) {
  621. if (is_array($data) && isset($field[$property]) && is_array($field[$property])) {
  622. // Combine field and @data-field together.
  623. $field[$property] += $data;
  624. } else {
  625. // Or create/replace field with @data-field.
  626. $field[$property] = $data;
  627. }
  628. }
  629. }
  630. }