XML.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. <?php
  2. Lib::loadClass('Core_XmlWriter');
  3. // $zxo = new XMLDiff\Memory;// @require xmldiff pecl package installed
  4. // TODO:TYPE_RECURCE: if type has local prefix - choose:
  5. // - find recurse typeName and restrictions
  6. // - find types and save in SystemObjectField table (if simpleType)
  7. // - ? find types and save in SystemObject table + SystemObjectField table (if complexType)
  8. class XML {
  9. public static function xmlToArray($xml) {
  10. }
  11. public static function readXmlFileToArray($filePath) {
  12. $z = new XMLReader();
  13. if (!$z) throw new HttpException("Class XMLReader not installed", 500);
  14. $fileName = basename($filePath);
  15. if (!$z->open($filePath)) throw new Exception("Failed to open ant schema file '{$fileName}'", 500);
  16. return self::xmlReadToArray($z);
  17. }
  18. public static function xmlReadToArray($z) {
  19. while ($z->read()) {
  20. if (XMLReader::ELEMENT !== $z->nodeType) continue;
  21. return self::xmlReadRecurse($z);
  22. }
  23. }
  24. public static function xmlReadRecurse($z) {
  25. $node = [ $z->name, [], [] ];// name, attrs, childrens
  26. $depth = $z->depth;
  27. $isEmpty = $z->isEmptyElement;
  28. if ($z->hasAttributes) {
  29. while ($z->moveToNextAttribute()) {
  30. $node[1][$z->name] = $z->value;
  31. }
  32. }
  33. if ($isEmpty) {
  34. $node[2] = null;
  35. return $node;
  36. }
  37. // switch ($z->name) {
  38. // case 'xsd:complexType': $node[1]['name'] = $z->getAttribute('name'); break;
  39. // case 'xsd:simpleType': $node[1]['name'] = $z->getAttribute('name'); break;
  40. // case 'xsd:restriction': $node[1]['base'] = $z->getAttribute('base'); break;
  41. // case 'xsd:enumeration': $node[1]['value'] = $z->getAttribute('value'); break;
  42. // case 'xsd:element': $node[1] = [
  43. // 'type' => $z->getAttribute('type')
  44. // ]; break;
  45. // case 'xsd:complexContent': break;
  46. // case 'xsd:sequence': break;
  47. // case 'xsd:attribute': $node[1]['base'] = $z->getAttribute('base'); break;
  48. // case 'xsd:extension': $node[1]['base'] = $z->getAttribute('base'); break;
  49. // default: UI::alert('warning', "TODO: read attributes from: d({$z->depth}) name($z->name)");
  50. // }
  51. while ($z->read() && $z->depth > $depth) {
  52. if (XMLReader::ELEMENT !== $z->nodeType) continue;
  53. // if ($z->depth == $depth + 2)
  54. $node[2][] = self::xmlReadRecurse($z);
  55. // else $node[2][] = "d({$z->depth}) name($z->name)";
  56. }
  57. return $node;
  58. }
  59. public static function printXmlFromArray($xml) {
  60. $xmlWriter = new Core_XmlWriter();
  61. $xmlWriter->openUri('php://output');
  62. $xmlWriter->setIndent(true);
  63. $xmlWriter->startDocument('1.0','UTF-8');
  64. $xmlWriter->h($xml[0], $xml[1], $xml[2]);
  65. $xmlWriter->endDocument();
  66. }
  67. public static function findTargetNamespace($docArray) {
  68. return V::get('targetNamespace', '', $docArray[1]);
  69. }
  70. public static function findSimpleTypeNode($docArray, $name) {
  71. foreach ($docArray[2] as $child) {
  72. if ('simpleType' === self::getTagName($child[0])) {
  73. if ($name === $child[1]['name']) {
  74. return $child;
  75. }
  76. }
  77. }
  78. }
  79. public static function findTargetNamespacePrefix($docArray) {
  80. $tns = self::findTargetNamespace($docArray);
  81. if (!$tns) throw new Exception("targetNamespace not defined");
  82. foreach ($docArray[1] as $attr => $val) {
  83. if ('xmlns:' !== substr($attr, 0, 6)) continue;
  84. if ($tns === $val) return substr($attr, 6);
  85. }
  86. throw new Exception("Missing targetNamespace xmlns:...");
  87. }
  88. public static function findElementName($docArray, $nodeArray) {
  89. if (!empty($nodeArray[1]['name'])) return $nodeArray[1]['name'];
  90. if (!empty($nodeArray[1]['ref'])) return $nodeArray[1]['ref'];
  91. throw new Exception("Missing xsd:element name");
  92. }
  93. public static function findElementType($docArray, $nodeArray) {
  94. $fieldName = self::findElementName($docArray, $nodeArray);
  95. if (!empty($nodeArray[1]['type'])) {
  96. // TODO:TYPE_RECURCE: if local ns prefix then find correct typeName?
  97. // TODO:TYPE_RECURCE:the same for restrictions
  98. $type = $nodeArray[1]['type'];
  99. if ('xs:' == substr($type, 0, 3)) return "xsd:" . substr($type, 3);
  100. if ('xsd:' == substr($type, 0, 4)) return $type;
  101. list($prefix, $name) = explode(':', $type);
  102. if ($prefix === self::findTargetNamespacePrefix($docArray)) {
  103. $simpleTypeNode = self::findSimpleTypeNode($docArray, $name);
  104. DBG::log($simpleTypeNode, 'array', "\$simpleTypeNode \$fieldName='{$fieldName}' type='{$type}'");
  105. if (!empty($simpleTypeNode[1]['type'])) {
  106. throw new Exception("TODO: findElementType node/@type => 'xsd:simpleType/@type' = '{$simpleTypeNode[1]['type']}'");
  107. }
  108. if (!empty($simpleTypeNode[2][0]) && 'xsd:restriction' == $simpleTypeNode[2][0][0]) {
  109. $restrictionNode = $simpleTypeNode[2][0];
  110. if (empty($restrictionNode[1]['base'])) throw new Exception("Missing xsd:restriction/@base (node/@type => xsd:simpleType/[@type='{$simpleTypeNode[1]['type']}']/xsd:restriction')");
  111. $type = $restrictionNode[1]['base'];
  112. DBG::log($type, 'array', "findElementType \$fieldName='{$fieldName}' type='{$nodeArray[1]['type']}' => type='{$type}'");
  113. // TODO: in findElementRestrictions or findSimpleTypeRestrictions - save current restrictions in $restrictionNode[2]
  114. // TODO: check restrictions - if has enumeration then return 'p5:enum'
  115. $isEnum = false;
  116. foreach ($restrictionNode[2] as $restr) {
  117. if ('enumeration' === self::getTagName($restr[0])) {
  118. $isEnum = true;
  119. break;
  120. }
  121. }
  122. if ($isEnum) return 'p5:enum';
  123. // TODO: recurse with limit
  124. if ('xs:' == substr($type, 0, 3)) return "xsd:" . substr($type, 3);
  125. if ('xsd:' == substr($type, 0, 4)) return $type;
  126. list($prefix, $name) = explode(':', $type);
  127. $simpleTypeNode = self::findSimpleTypeNode($docArray, $name);
  128. DBG::log($simpleTypeNode, 'array', "\$simpleTypeNode \$fieldName='{$fieldName}' ... type='{$type}'");
  129. if (!empty($simpleTypeNode[1]['type'])) {
  130. throw new Exception("TODO: findElementType node/@type => 'xsd:simpleType/@type' = '{$simpleTypeNode[1]['type']}'");
  131. }
  132. if (!empty($simpleTypeNode[2][0]) && 'xsd:restriction' == $simpleTypeNode[2][0][0]) {
  133. $restrictionNode = $simpleTypeNode[2][0];
  134. if (empty($restrictionNode[1]['base'])) throw new Exception("Missing xsd:restriction/@base (node/@type => xsd:simpleType/[@type='{$simpleTypeNode[1]['type']}']/xsd:restriction')");
  135. $type = $restrictionNode[1]['base'];
  136. DBG::log($type, 'array', "findElementType \$fieldName='{$fieldName}' ... type='{$type}'");
  137. if ('xs:' == substr($type, 0, 3)) return "xsd:" . substr($type, 3);
  138. if ('xsd:' == substr($type, 0, 4)) return $type;
  139. }
  140. // TODO: throw...
  141. }
  142. // TODO: throw...
  143. // 0 => 'xsd:simpleType',
  144. // 1 => [
  145. // 'name' => 'PROCES_INIT_Simple',
  146. // ],
  147. // 2 => [
  148. // 0 => [
  149. // 0 => 'xsd:restriction',
  150. // 1 => [
  151. // 'base' => 'default_db__x3A__CRM_PROCES:TYPE_Simple',
  152. // ],
  153. // 2 => [
  154. // 0 => [
  155. // 0 => 'xsd:enumeration',
  156. // 1 => [
  157. // 'value' => 'PROCES_INIT',
  158. // ],
  159. // 2 => NULL,
  160. } else {
  161. return $nodeArray[1]['type'];
  162. }
  163. }
  164. if (!empty($nodeArray[1]['ref'])) return 'ref:' . $nodeArray[1]['ref'];
  165. if (empty($nodeArray[2])) throw new Exception("Missing xsd:element childrens - cannot find type");
  166. // TODO: find in loop (xsd:annotation may accure)
  167. if (empty($nodeArray[2][0][0]) || 'xsd:simpleType' != $nodeArray[2][0][0]) throw new Exception("Missing 'xsd:simpleType' for field '{$fieldName}'");
  168. if (empty($nodeArray[2][0][2][0]) || 'xsd:restriction' != $nodeArray[2][0][2][0][0]) throw new Exception("Missing 'xsd:restriction' for field '{$fieldName}'");
  169. if (empty($nodeArray[2][0][2][0][1]['base'])) throw new Exception("Missing 'xsd:restriction/@base' for field '{$fieldName}'");
  170. return $nodeArray[2][0][2][0][1]['base'];
  171. }
  172. public static function findElementRestrictions($docArray, $nodeArray) {
  173. $restrictions = [];
  174. $fieldName = self::findElementName($docArray, $nodeArray);
  175. // TODO:TYPE_RECURCE: if type has local prefix then find retriction recurse?
  176. if (!empty($nodeArray[1]['nillable']) && 'true' === $nodeArray[1]['nillable']) $restrictions['nillable'] = true;
  177. if (!empty($nodeArray[2])) {
  178. foreach ($nodeArray[2] as $c) {
  179. switch (XML::getTagName($c[0])) {
  180. case 'annotation': break; // skip xsd:element/xsd:annotation @see findElementAppInfo
  181. case 'simpleType': { // xsd:element/xsd:simpleType
  182. if (empty($c[2][0]) || 'restriction' != XML::getTagName($c[2][0][0])) throw new Exception("Missing 'xsd:restriction' for field '{$fieldName}'");
  183. if (empty($c[2][0][1]['base'])) throw new Exception("Missing 'xsd:restriction/@base' for field '{$fieldName}'");
  184. // xsd:element/xsd:simpleType/xsd:restriction/xsd:string
  185. foreach ($c[2][0][2] as $tagRestriction) {
  186. // xsd:string/xsd:maxLength
  187. $val = $tagRestriction[1]['value'];
  188. if ('enumeration' == XML::getTagName($tagRestriction[0])) {
  189. $restrictions['enumeration'][$val] = $val;
  190. } else {
  191. $restrictions[XML::getTagName($tagRestriction[0])] = $val;
  192. }
  193. }
  194. } break;
  195. default: {
  196. DBG::log($c, 'array', "Not imeplemented element child '{$c[0]}'");
  197. }
  198. }
  199. }
  200. }
  201. return $restrictions;
  202. }
  203. public static function findElementAppInfo($docArray, $nodeArray) {
  204. $appInfo = [];
  205. $fieldName = self::findElementName($docArray, $nodeArray);
  206. if (!empty($nodeArray[2])) {
  207. foreach ($nodeArray[2] as $c) {
  208. switch (XML::getTagName($c[0])) {
  209. case 'annotation': { // skip xsd:element/xsd:annotation
  210. DBG::nicePrint($c, "TODO: xsd:annotation/xsd:appinfo '{$fieldName}'");
  211. // <xsd:annotation>
  212. // <xsd:appinfo>
  213. // <system_cache__appinfo:flat_relation_cache>
  214. // <system_cache__appinfo:source system_cache__appinfo:name="ID"
  215. // system_cache__appinfo:xpath="default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK/ID_PROCES"/>
  216. $prefix = 'system_cache__appinfo';
  217. foreach ($c[2] as $cc) {
  218. if ('appinfo' == XML::getTagName($cc[0])) {
  219. foreach ($cc[2] as $appTag) {
  220. $appInfo[XML::getTagName($appTag[0])] = XML::readAppInfoRecurse($docArray, $appTag);
  221. }
  222. }
  223. }
  224. } break;
  225. case 'simpleType': break; // skip xsd:element/xsd:simpleType @see findElementRestrictions
  226. default: {
  227. DBG::log($c, 'array', "Not imeplemented element child '{$c[0]}'");
  228. }
  229. }
  230. }
  231. }
  232. DBG::log($fieldName, 'array', "findElementAppInfo fieldName='{$fieldName}'");
  233. return $appInfo;
  234. }
  235. public static function getTagName($xsdName) {
  236. return (false !== ($pos = strpos($xsdName, ':')))
  237. ? substr($xsdName, $pos + 1)
  238. : $xsdName;
  239. }
  240. public static function readAppInfoRecurse($docArray, $nodeArray) {
  241. $appInfo = [];
  242. if (!empty($nodeArray[1])) foreach ($nodeArray[1] as $attrName => $attrVal) {
  243. $appInfo['@' . XML::getTagName($attrName)] = $attrVal;
  244. }
  245. if (!empty($nodeArray[2])) foreach ($nodeArray[2] as $appTag) {
  246. $appInfo[XML::getTagName($appTag[0])] = XML::readAppInfoRecurse($docArray, $appTag);
  247. }
  248. // TODO: text nodes
  249. return $appInfo;
  250. }
  251. public static function findFieldsFromSequence($docArray, $nodeArray) {
  252. if ($nodeArray[0] != 'xsd:sequence') throw new Exception("Error Parsing Schema - expected 'sequence'");
  253. $fields = [];
  254. foreach ($nodeArray[2] as $f) {
  255. if ($f[0] !== 'xsd:element') {
  256. DBG::log($n, 'array', "Schema xsd parse error - Not implemented node type '{$f[0]}'");
  257. continue;
  258. }
  259. $fieldName = XML::findElementName($docArray, $f); // V::get('name', '', $f[1]);
  260. if (!$fieldName) throw new Exception("Error Parsing Schema - expected 'element[@name]'");
  261. if ('__' === substr($fieldName, 0, 2)) continue;
  262. if (!V::get('type', '', $f[1]) && !V::get('ref', '', $f[1]) && empty($f[2])) {
  263. UI::alert('danger', "Skipping not implemented field structure '{$fieldName}'");
  264. DBG::log($f, 'array', "Skipping not implemented field structure '{$fieldName}'");
  265. continue;
  266. }
  267. $fields[$fieldName] = [
  268. 'type' => XML::findElementType($docArray, $f),
  269. 'minOccurs' => V::get('minOccurs', 0, $f[1], 'int'),
  270. 'maxOccurs' => V::get('maxOccurs', '1', $f[1]),
  271. 'restrictions' => XML::findElementRestrictions($docArray, $f),
  272. 'appInfo' => XML::findElementAppInfo($docArray, $f),
  273. ];
  274. }
  275. return $fields;
  276. }
  277. public static function findFieldsFromComplexContent($docArray, $nodeArray) {
  278. // xsd:complexType / xsd:complexContent / xsd:restriction [ @base = "default_db__x3A__CRM_PROCES:CRM_PROCES" ]
  279. // xsd:complexType / xsd:complexContent / xsd:extension [ @base = "default_db__x3A__CRM_PROCES:CRM_PROCES" ]
  280. switch (XML::getTagName($nodeArray[2][0][0])) {
  281. case 'extension': return XML::findFieldsFromExtension($docArray, $nodeArray[2][0]);
  282. case 'restriction': return XML::findFieldsFromRestriction($docArray, $nodeArray[2][0]);
  283. }
  284. // TODO:? $xsdType['extensionBase'] = V::get('base', '', $nodeArray[1]);
  285. // TODO:? $xsdType['restrictionBase'] = V::get('base', '', $nodeArray[1]);
  286. }
  287. public static function findFieldsFromExtension($docArray, $nodeArray) {
  288. $fields = [];
  289. if ($nodeArray[2][0][0] != 'xsd:sequence') throw new Exception("Error Parsing Schema - expected 'complexType/complexContent/extension/sequence'");
  290. foreach ($nodeArray[2][0][2] as $f) {
  291. if ($f[0] !== 'xsd:element') {
  292. DBG::log($n, 'array', "Schema xsd parse error - Not implemented node type '{$f[0]}'");
  293. continue;
  294. }
  295. $fieldName = XML::findElementName($docArray, $f); // V::get('name', '', $f[1]);
  296. if (!$fieldName) throw new Exception("Error Parsing Schema - expected 'element[@name]'");
  297. if ('__' === substr($fieldName, 0, 2)) continue;
  298. if (!V::get('type', '', $f[1]) && !V::get('ref', '', $f[1]) && empty($f[2])) {
  299. UI::alert('danger', "Skipping not implemented field structure '{$fieldName}'");
  300. continue;
  301. }
  302. $fields[$fieldName] = [
  303. 'type' => XML::findElementType($docArray, $f),
  304. 'minOccurs' => V::get('minOccurs', 0, $f[1], 'int'),
  305. 'maxOccurs' => V::get('maxOccurs', '1', $f[1]),
  306. 'restrictions' => XML::findElementRestrictions($docArray, $f),
  307. 'appInfo' => XML::findElementAppInfo($docArray, $f),
  308. ];
  309. }
  310. return $fields;
  311. }
  312. public static function findFieldsFromRestriction($docArray, $nodeArray) {
  313. $fields = [];
  314. if ($nodeArray[2][0][0] != 'xsd:sequence') throw new Exception("Error Parsing Schema - expected 'complexType/complexContent/restriction/sequence'");
  315. foreach ($nodeArray[2][0][2] as $f) {
  316. if ($f[0] !== 'xsd:element') {
  317. DBG::log($n, 'array', "Schema xsd parse error - Not implemented node type '{$f[0]}'");
  318. continue;
  319. }
  320. $fieldName = XML::findElementName($docArray, $f); // V::get('name', '', $f[1]);
  321. if (!$fieldName) throw new Exception("Error Parsing Schema - expected 'element[@name]'");
  322. if ('__' === substr($fieldName, 0, 2)) continue;
  323. if (!V::get('type', '', $f[1]) && !V::get('ref', '', $f[1]) && empty($f[2])) {
  324. UI::alert('danger', "Skipping not implemented field structure '{$fieldName}'");
  325. continue;
  326. }
  327. $fields[$fieldName] = [
  328. 'type' => XML::findElementType($docArray, $f),
  329. 'minOccurs' => V::get('minOccurs', 0, $f[1], 'int'),
  330. 'maxOccurs' => V::get('maxOccurs', '1', $f[1]),
  331. 'restrictions' => XML::findElementRestrictions($docArray, $f),
  332. 'appInfo' => XML::findElementAppInfo($docArray, $f),
  333. ];
  334. }
  335. return $fields;
  336. }
  337. }