4 * Parses string hash files. File format is as such:
13 * Which would output something similar to:
16 * 'ID' => 'DefaultKeyValue',
19 * 'MULTILINE-KEY' => "Multiline\nvalue.\n",
22 * We use this as an easy to use file-format for configuration schema
23 * files, but the class itself is usage agnostic.
25 * You can use ---- to forcibly terminate parsing of a single string-hash;
26 * this marker is used in multi string-hashes to delimit boundaries.
28 class HTMLPurifier_StringHashParser
31 public $default = 'ID';
34 * Parses a file that contains a single string-hash.
36 public function parseFile($file) {
37 if (!file_exists($file)) return false;
38 $fh = fopen($file, 'r');
39 if (!$fh) return false;
40 $ret = $this->parseHandle($fh);
46 * Parses a file that contains multiple string-hashes delimited by '----'
48 public function parseMultiFile($file) {
49 if (!file_exists($file)) return false;
51 $fh = fopen($file, 'r');
52 if (!$fh) return false;
54 $ret[] = $this->parseHandle($fh);
61 * Internal parser that acepts a file handle.
62 * @note While it's possible to simulate in-memory parsing by using
63 * custom stream wrappers, if such a use-case arises we should
64 * factor out the file handle into its own class.
65 * @param $fh File handle with pointer at start of valid string-hash
68 protected function parseHandle($fh) {
74 if ($line === false) break;
75 $line = rtrim($line, "\n\r");
76 if (!$state && $line === '') continue;
77 if ($line === '----') break;
78 if (strncmp('--#', $line, 3) === 0) {
81 } elseif (strncmp('--', $line, 2) === 0) {
82 // Multiline declaration
83 $state = trim($line, '- ');
84 if (!isset($ret[$state])) $ret[$state] = '';
88 if (strpos($line, ':') !== false) {
89 // Single-line declaration
90 list($state, $line) = explode(':', $line, 2);
93 // Use default declaration
94 $state = $this->default;
102 $ret[$state] .= "$line\n";
104 } while (!feof($fh));
110 // vim: et sw=4 sts=4