* Follow-up r84397: make sure that mysql uses the job_id index even with the job_cmd...
[lhc/web/wiklou.git] / includes / XmlTypeCheck.php
1 <?php
2
3 class XmlTypeCheck {
4 /**
5 * Will be set to true or false to indicate whether the file is
6 * well-formed XML. Note that this doesn't check schema validity.
7 */
8 public $wellFormed = false;
9
10 /**
11 * Will be set to true if the optional element filter returned
12 * a match at some point.
13 */
14 public $filterMatch = false;
15
16 /**
17 * Name of the document's root element, including any namespace
18 * as an expanded URL.
19 */
20 public $rootElement = '';
21
22 /**
23 * @param $file string filename
24 * @param $filterCallback callable (optional)
25 * Function to call to do additional custom validity checks from the
26 * SAX element handler event. This gives you access to the element
27 * namespace, name, and attributes, but not to text contents.
28 * Filter should return 'true' to toggle on $this->filterMatch
29 */
30 function __construct( $file, $filterCallback=null ) {
31 $this->filterCallback = $filterCallback;
32 $this->run( $file );
33 }
34
35 /**
36 * Get the root element. Simple accessor to $rootElement
37 *
38 * @return string
39 */
40 public function getRootElement() {
41 return $this->rootElement;
42 }
43
44 /**
45 * @param $fname
46 */
47 private function run( $fname ) {
48 $parser = xml_parser_create_ns( 'UTF-8' );
49
50 // case folding violates XML standard, turn it off
51 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
52
53 xml_set_element_handler( $parser, array( $this, 'rootElementOpen' ), false );
54
55 $file = fopen( $fname, "rb" );
56 do {
57 $chunk = fread( $file, 32768 );
58 $ret = xml_parse( $parser, $chunk, feof( $file ) );
59 if( $ret == 0 ) {
60 // XML isn't well-formed!
61 fclose( $file );
62 xml_parser_free( $parser );
63 return;
64 }
65 } while( !feof( $file ) );
66
67 $this->wellFormed = true;
68
69 fclose( $file );
70 xml_parser_free( $parser );
71 }
72
73 /**
74 * @param $parser
75 * @param $name
76 * @param $attribs
77 */
78 private function rootElementOpen( $parser, $name, $attribs ) {
79 $this->rootElement = $name;
80
81 if( is_callable( $this->filterCallback ) ) {
82 xml_set_element_handler( $parser, array( $this, 'elementOpen' ), false );
83 $this->elementOpen( $parser, $name, $attribs );
84 } else {
85 // We only need the first open element
86 xml_set_element_handler( $parser, false, false );
87 }
88 }
89
90 /**
91 * @param $parser
92 * @param $name
93 * @param $attribs
94 */
95 private function elementOpen( $parser, $name, $attribs ) {
96 if( call_user_func( $this->filterCallback, $name, $attribs ) ) {
97 // Filter hit!
98 $this->filterMatch = true;
99 }
100 }
101 }